First - this isn't meant as a question whether using gotos is appropriate to use in an OO langauge. That's been overdone, so please don't let it degenerate to that type of discussion.
I DID however use a goto recently in a nested loop to escape it, and it got me thinking about the variables used in a loop, and the flow.
I tested the following minimal, working, c++ code:
#include <iostream>
using namespace std;
int main ()
{
if (true)
{
for ( int i = 0 ; i < 3; i++)
{
looped:
cout << i << " ";
}
}
cout << "\nexit loop\n";
int j = -1;
// cout << i; // does not compile, obviously as expected
goto looped;
}
This actually ends up printing:
0
1
2
exit loop
3
exit loop
4
exit loop
5
exit loop
6
And so on, forever
So... I expected i to be popped off the stack once the loop exited naturally (the first time), and the declaration of j to replace it on the stack.
I'm using Visual Studio 2012 Express to test this. I haven't tested it on anything else yet. Why does it look like the declaration of i isn't popped off the stack at all?
This also makes me wonder what happens when I use a goto to escape the loop - does the variable declared in the loop's header stay on the stack? It seems like it should, but after this experiment, I'm not feeling too confident in how I know the stack to work.
Anyone have any comments?