Home > Backend Development > C++ > When are Static Variables Initialized?

When are Static Variables Initialized?

Susan Sarandon
Release: 2024-11-27 02:38:10
Original
509 people have browsed it

When are Static Variables Initialized?

Static Variable Allocation and Initialization

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?

Allocation of Static Variables

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.

Initialization of Static Variables

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
  // ...
}
Copy after login

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!

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