I’m quite confident that globally declared variables get allocated (and initialized, if applicable) at program start time.
int globalgarbage; unsigned int anumber = 42;
But what about static ones defined within a function?
void doSomething() { static bool globalish = true; // ... }
When is the space for globalish allocated? I’m guessing when the program starts. But does it get initialized then too? Or is it initialized when doSomething() is first called?
I was curious about this so I wrote the following test program and compiled it with g++ version 4.1.2.
The results were not what I expected. The constructor for the static object was not called until the first time the function was called. Here is the output: