What is the life span of a variable inside a block?

Here and Here, I found that the variables in the block are created when it reaches this block,

To prove that I tried this:

int main() { { char a; printf("Address of a %d \n",&a); } char b; printf("Address of b %d \n",&b); } 

As expected, b was first created (because the outer block executes earlier than the inner one), and when the execution executed by the inner block a was created. The output of the above code:

 Address of a 2686766 Address of b 2686767 

(Tested on x86 (the stack grows down, so a variable with a large address was created first)).

But what about this ?:

 int main() { { char a; printf("Address of a %d \n",&a); } // I expected that variable a should be destroyed here { char b; printf("Address of b %d \n",&b); } } 

Output:

 Address of a 2686767 Address of b 2686766 

I expected that a was destroyed when closing the brackets of the first block, so the address where it was located is now on top of the stack, and b should be created here, so in the output above both addresses should be equal, but aren't they? Are variables shuffled at the end of the block? If not, why?

+6
source share
2 answers

There are no rules for how the compiler puts variables into memory. He can very well reserve a place for both of them at the same time, if it is "easier" in some way.

Allowed to reuse space for variables in different areas, but not required. Saving one byte may not be worth trying to "optimize" the allocation.

+10
source

Deleting a variable in C ++ means "calling the destructor." Nothing more, nothing more. Since char built-in types do not have destructors, their destruction is not visible to the observer.

0
source

All Articles