Lifetime of Static Variables in C Functions
Declaring a variable as static within a function's scope ensures its initialization only once, maintaining its value across function invocations. Understanding its precise lifetime is crucial.
When Are Static Variables Created and Destroyed?
Static variables in a function have a lifetime that spans from the first encounter with their declaration to program termination. This means that:
Tracking Construction/Destruction Order
Determining the order of construction and destruction of static variables is essential, especially in multi-threaded environments. The standard dictates that destructors of static objects are executed in the reverse order of construction completion.
Implementation Example
Consider the following code snippet:
struct emitter { string str; emitter(const string& s) : str(s) { cout << "Created " << str << endl; } ~emitter() { cout << "Destroyed " << str << endl; } }; void foo(bool skip_first) { if (!skip_first) static emitter a("in if"); static emitter b("in foo"); } int main(int argc, char*[]) { foo(argc != 2); if (argc == 3) foo(false); }
Output:
C:>sample.exe Created in foo Destroyed in foo C:>sample.exe 1 Created in if Created in foo Destroyed in foo Destroyed in if C:>sample.exe 1 2 Created in foo Created in if Destroyed in if Destroyed in foo
This demonstrates the lifetime and construction/destruction order of static variables.
The above is the detailed content of How Long Do Static Variables in C Functions Live?. For more information, please follow other related articles on the PHP Chinese website!