I want to use a variable inside a loop, but I don't want it to be re-declared on every iteration. Obviously I can declare it outside of the loop but I wondered what would happen if I declared it as static inside the loop.
To test this I declared both a static and a non-static variable inside a while loop and printed their memory addresses on each iteration. I expected the address of the non-static variable to keep changing and that of the static to stay the same.
while (true)
{
int var1;
static int var2;
cout << &var1 << "\n"
<< &var2 << endl;
}
Results: To my surprise the addresses of both variables stayed the same.
- Is this some kind of compiler optimization or was I wrong to assume that re-declaring the non-static variable should yield a different address on every iteration? I'm using gcc 9.3.0 with no optimization flags.
- Is the static variable a good alternative to declaring a non-static variable outside of the loop (assuming I won't need it in the outer scope and I'm not concerned that the variable will retain its last value in case the loop is entered again at a later time)?