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
?