Hamiral said:
Well I guess that the space used by i in the loop can be, after the
loop, used by variable declared after it...
For example :
int main(void)
{
int *p;
if(1) {
int i = 12;
p = &i;
}
int j = 42;
printf("i = %d\n", *p);
return 0;
}
Here the space used by i in the loop could be recycled and used for j,
so the output could be i = 42
Well, yes and no (or perhaps I should say no and yes).
The lifetime of any object with automatic storage duration begins on
entry to the block with which it is associated, and ends when
execution of the block ends. So the lifetime of j actually begins at
the opening brace, even though it's not visible until the declaration
is reached. Since the lifetimes of i and j overlap, they can't share
the same storage. (It's actually possible to access j before its
declaration is reached by saving its address somewhere and jumping to
the top of the block with a goto statement.)
On the other hand, the program's behavior is undefined, so the
implementation is free to make i and j share storage (though I can't
think of any good reason to do so).
On the other other hand, two objects whose lifetimes overlap, but
whose effective lifetimes are disjoint, can share the same storage if
the compiler is clever enough to perform such an optimization.
"Effective lifetime" is a term I just made up. Here's an example:
{
int i = 42;
printf("i = %d\n", i);
/* i is not used after this */
/* j is not used before this */
int j = 43;
printf("j = %d\n", j);
}
i and j are two distinct objects, but the compiler can make them share
the same storage as long as it doesn't affect the behavior of the
program. Shuffle the statements around a bit, and the optimization
becomes invalid.