Below is the code that I used as a reference to understand how the area of ββa sub-item (or) of a fictitious area (just {} ) present in a function affects the structure of the stack frame.
#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; }
Output example
main_scope++:(1) Value of redefined main_scope:(2) Finally main_scope in main:(1)
Based on the above behavior, I assume the following.
- For area
{} there is no stack stack structure. - Thus, the
auto variables declared / defined in main , and those in subparagraph {} , have the same frame stack. - Thus, variables declared / defined in
main can be accessed anywhere in the function (even within the scope). - On the other hand, variables declared / defined in a subclause lose their scope outside the block. But its lifespan is valid as long as the stack stack is present.
Question: If the above points are correct, then why does the code not work when providing multiple definitions of the same variable, one inside main and the other in {} .
source share