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)?
main
and from another function (that is called bymain
). Then you should see a difference. – Some programmer dudevar1
andvar2
have the exact same scope. Thestatic
storage duration ofvar2
means that its life-time will be the whole programs full run-time. Localstatic
variables are also guaranteed to be zero-initialized, unless explicitly initialized some other way, and also the initialization (and only initialization) is guaranteed to be thread-safe and happen only once. – Some programmer dudestatic
option is going to add some synchronisation to the code as functionstatic
objects are guaranteed to only be initialised once in multi-threaded code. – Richard Critten