Search code examples
c++staticinitializationvariable-assignmentmodifiers

Why does the static modifier prevent its variable to be reassigned with a new value?


A minimal working example is as follows:

#include <iostream>

void func()
{
    static int i = 5;
    std::cout << i << std::endl;
    i = 42;
    std::cout << i << std::endl;
}

int main( int argc, char ** argv )
{
    std::cout << "this is main()" << std::endl;
    func();
    func();
    return 0;
}

Its output is as follows:

this is main()
i is 5
i is 42
i is 42
i is 42

Static modifier for the variable int makes int's value persistent for the life of the entire process while static storage is not stored on the stack; thus, the value is carried from one invocation of the function to another.

However, int is re-assigned to the value of 5 at the beginning of func() when func() is called second time.

So, why does this example output i = 42 instead of i = 5?


Solution

  • However, int is re-assigned to the value of 5 at the beginning of func() when func() is called second time.

    No, this is not assignment, but initialization. Static local variables are initialized only once, i.e. when func() is called for the first time.

    Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.