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?
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?
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).
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.
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.
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, ...)