具有子作用域的函数的堆栈帧结构

Viv*_*ran 5 c scope stack-frame storage-class-specifier

以下是代码,我将其作为参考,以了解{}函数中存在的子作用域(或)虚拟作用域(仅)如何影响堆栈帧的结构。

#include <stdio.h>
int main()
{
   int main_scope=0; /*Scope and life time of the variable is throughout main*/

   {
     //From below two statements I assume that there
     //is no seperate "stack frame" created for just
     //braces {}.So we are free access (scope exists) and
     //modify (lifetime exists) the variable "main_scope"
     //anywhere within main

     main_scope++;
     printf("main_scope++:(%d)\n",main_scope);

    //I expected this statement to throw an error saying
    //"Multiple definition for "main_scope".But it isn't????

    int main_scope=2;
    printf("Value of redefined main_scope:(%d)\n",main_scope);

  }

  printf("Finally main_scope in %s:(%d)\n",__FUNCTION__,main_scope);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

样本输出

main_scope++:(1)
Value of redefined main_scope:(2)
Finally main_scope in main:(1)
Run Code Online (Sandbox Code Playgroud)

基于上述行为,我推测如下。

  • 没有为作用域创建堆栈帧{}
  • 通过这种方式auto,在子作用域中声明/定义的变量main和子作用域内的变量{}共享相同的堆栈帧。
  • 因此,声明/定义的变量main可以在函数内的任何位置(甚至在子作用域内)自由访问。
  • 另一方面,在子作用域中声明/定义的变量在块之外失去其作用域。但只要堆栈帧存在,其生命周期就有效。

问题:如果上述观点是正确的,那么为什么在给出同一变量的多个定义(一个在 内,main另一个在{}.

Ale*_*nze 2

硬件堆栈在这里无​​关紧要。对于所有局部变量,它只能在函数入口处增长一次,并在函数出口处收缩一次,或者每次定义新的局部变量时,它都可以增长和收缩,并在保留其封闭的 {} 时销毁。

相关的是变量的“可见性”。

int main_scope=0;

{
    main_scope++;
    printf("main_scope++:(%d)\n",main_scope);
    // the main_scope variable that was assigned 0 is the most recent
    // visible declaration of main_scope.

    int main_scope=2;
    // now, the previous declaration of main_scope is obscured by the new one,
    // and so, you're going to access the new one
    printf("Value of redefined main_scope:(%d)\n",main_scope);
}

printf("Finally main_scope in %s:(%d)\n",__FUNCTION__,main_scope);
// the previous scope inside {} is left, so, main_scope is going to be
// the one, to which we assigned 0
Run Code Online (Sandbox Code Playgroud)

在内部/子作用域中定义与外部/超级作用域中同名的对象是完全合法的。后者将在 {} 作用域的持续时间内被隐藏。

仅供参考,还有一些其他地方可以出现变量定义,例如在语句的第一个表达式内for(;;)for (int i = 0; i < 10; i++) ...。该变量i仅在 for 主体内可见,您也可以通过定义另一个i.