I tried this code on Visual C++ 2008 and it shows that A and B don't have the same address.
int main()
{
{
int A;
printf("%p\n", &A);
}
int B;
printf("%p\n", &B);
}
But since A doesn't exist anymore when B gets defined, it seems to me that the same stack location could be reused...
I don't understand why the compiler doesn't seem to do what looks like a very simple optimization (which could matter in the context of larger variables and recursive functions for example). And it doesn't seem like reusing it would be heavier on the CPU nor the memory. Does anyone have an explanation for this?
I guess the answer is along the lines of "because it's much more complex than it looks", but honestly I have no idea.
edit: Some precisions regarding the answers and comments below.
The problem with this code is that each time this function is called, the stack grows "one integer too much". Of course this is no problem in the example, but consider large variables and recursive calls and you have a stack overflow that could be easily avoided.
What I suggest is a memory optimization, but I don't see how it would damage performance.
And by the way, this happens in release builds, will all optimizations on.