Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 8 down vote accepted

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

share|improve this answer
2  
I would posit that worrying too much about how the compiler handles this would be premature optimization for most applications. –  TehShrike Dec 18 '11 at 20:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.