Are Block-Scope Variables in C/C++ Stacked Only if the Block is Executed?

allocationcstack

Suppose this:

void func()
{
 ...
 if( blah )
 {
  int x;
 }
 ...
}  

Is the space for x reserved on the stack immediately when func is entered, or only if the block is actually executed?
Or is it the compiler's choice?
Do C and C++ behave the same about this?

Best Answer

Who said the compiler will reserve any space (could be register only).

This is completely undefined.
All that you can say is that it (x) can only be accessed from inside the inner block.

How the compiler allocates memory (on a stack if it even exists) is completely upto the compiler (as the memory region may be re-used for multiple objects (if the compiler can prove that their lifespans do not overlap)).

Is the space for x reserved on the stack immediately when func is entered

Undetermined.

or only if the block is actually executed?

Undetermined.
But if x was a class object then the constructor will only be run if the block is entered.

Or is it the compiler's choice?

The compiler may not even allocate memory.

Do C and C++ behave the same about this?

Yes

Related Topic