tags:

views:

184

answers:

4

Hi,

I have a loop as follows

while(1)
{
    int i;
}

Does i get destroyed and recreated on the stack each time the loop occurs?

+13  A: 

Theoretically, it gets recreated. In practice, it might be kept alive and reinitalized for optimization reasons.

But from your point of view, it gets recreated, and the compiler handles the optimization (i.e, keep it at it's innermost scope, as long as it's a pod type).

Viktor Sehr
so do I have to worry about stack issues if I have several such declarations in a loop that runs a lot of times?
Rajesh
absolutely not.
Viktor Sehr
Btw I thought the question regarded optimization
Viktor Sehr
+2  A: 

Conceptually, yes. But since there's nothing being done to the value, the compiler is very likely to generate code does nothing with the variable on each iteration of the loop. It can, for instance, allocate it in advance (when the function enters), since it's going to be used later.

Since you can't reference the variable outside the defining scope, that doesn't change the semantics.

unwind
+3  A: 

Not necessarily. Your compiler could choose to change it into

int i;
while(1) { 
     ...
     i = 0; 
}

It may not be literally created and destroyed on the stack every time. However, semantically, that is what occurs,and when you use more complex types in C++ that have custom destruction behaviour then that is exactly what happens, although the compiler may still choose to hold the stack memory separately.

DeadMG
Where does the `i = 0` come from? Stack variables have no default values in C or C++.
FredOverflow
I was thinking about resetting the value of i, else it's destruction semantics would not be preserved, but since I realized that the OP didn't initialize his i that it's value was actually undefined and any compiler doesn't need to insert that.
DeadMG
+2  A: 

In C you have to look at the assembly generated to know that (the compiler might have chosen to put it in a register).

What you know is that outside the loop you cannot access that particular object by any means (by name, by pointer, by hack, ...)

pmg