Home > Article > Backend Development > When and How Are Function-Level Static Variables in C Allocated and Initialized?
Allocation and Initialization of Function-Level Static Variables
Function-level static variables in C are a type of data that persists throughout the lifetime of the program. Unlike global variables, they are not declared at the global scope, but rather within the scope of a function. This raises疑問 about when these variables are allocated and initialized.
In contrast to globally declared variables, which are allocated and initialized at the start of the program, function-level static variables are allocated and initialized upon the first call to the function in which they are defined. This is evident in the example code provided:
void doSomething() { static bool globalish = true; }
The static variable globalish is initialized upon the first call to the function doSomething. Prior to that, its value is undefined. This result was confirmed through a test program that printed events related to the creation and destruction of objects instantiated within different scopes.
This behavior is attributed to the fact that static variables are stored in a static area of memory that is shared among all calls to the same function. Thus, the initial value remains persistent across calls, unless explicitly modified within the function.
The above is the detailed content of When and How Are Function-Level Static Variables in C Allocated and Initialized?. For more information, please follow other related articles on the PHP Chinese website!