Home > Backend Development > C++ > How Long Do Static Variables in C Functions Live?

How Long Do Static Variables in C Functions Live?

Patricia Arquette
Release: 2024-12-30 14:03:22
Original
1012 people have browsed it

How Long Do Static Variables in C   Functions Live?

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:

  • The constructor is called during the initial declaration.
  • The destructor is called upon program termination or when the variable goes out of scope (e.g., function exit).

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);
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template