Home >Backend Development >C++ >What is the Lifetime and Initialization/Deinitialization Behavior of Static Variables in C Functions?

What is the Lifetime and Initialization/Deinitialization Behavior of Static Variables in C Functions?

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 14:19:22904browse

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:

  • Initialization: Occurs the first time the program execution reaches the variable declaration, ensuring its initialization only once.
  • Deinitialization: Unlike automatic variables, function statics are deinitialized at program termination, guaranteeing proper resource release.

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!

Statement:
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