A static variable has a global lifetime but with local scope. This lets you have the benefits of having a singular global and the organizational benefit of keeping the scope local.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void CountIt()
{
staticint count = 0;
++count;
cout << count << "\n";
}
int main()
{
CountIt(); // prints 1
CountIt(); // prints 2
CountIt(); // prints 3, etc
}
It's initialized only once (barring some unfortunate multithreaded race condition)
Static and global data is initialized before main() is called, one object at a time. There's no room for race conditions because it's all ran from a single thread.