Home >Backend Development >C++ >What is the Lifetime and Initialization/Deinitialization Behavior of Static Variables in C Functions?
Lifetime of Static Variables in C Functions
When a variable is declared as static within a function, it is initialized only once and its value is retained throughout subsequent function calls. However, determining its precise lifetime is crucial for understanding its behavior.
The lifetime of a function static variable encompasses:
Regarding its constructor and destructor calls, the C standard specifies that they are called automatically during initialization and deinitialization, respectively. This ensures appropriate object creation and destruction.
Lifetime Example
Consider the following code snippet:
void foo() { static string plonk = "When will I die?"; }
In this example, the static variable plonk is initialized when the execution enters the foo function for the first time. Since it's static, its value will persist throughout subsequent calls to foo. At program termination, plonk's destructor will be called, destroying the variable.
Additionally, for each program run, the order of construction and destruction of static variables may vary, leading to different outputs.
The above is the detailed content of What is the Lifetime and Initialization/Deinitialization Behavior of Static Variables in C Functions?. For more information, please follow other related articles on the PHP Chinese website!