When it comes to variable allocation and initialization, the timing can vary depending on the scope of the variable. Global variables, as mentioned, are allocated at program startup. But what about static variables declared within functions?
In the given scenario, the static variable globalish is allocated when the program starts, similar to global variables. This is because static variables have a longer lifespan than local variables, maintaining their values even when the function they're defined in exits.
The initialization timing of static variables is where things get interesting. Unlike global variables, static variables are not initialized at program startup. Instead, they're initialized only when the function they belong to is first called. This behavior is evident in the provided example program:
void doSomething() { static bool globalish = true; // Initialization occurs here // ... }
In this case, the initialization of globalish happens when doSomething() is first executed, not at the time the program starts. This late initialization is referred to as "lazy initialization."
The reason for this delayed initialization is to avoid unnecessary initialization for static variables that may never be used. If the program never calls the function that declares the static variable, it saves memory and computation time by not initializing it.
The above is the detailed content of When are Static Variables Initialized?. For more information, please follow other related articles on the PHP Chinese website!