Static variable
A static variable in C++ is a variable that is allocated once and remains in memory throughout the execution of the program. Static variables can be declared at global scope, namespace scope, class scope, or function scope.
Static variables at global scope are initialized when the program starts and are destroyed when the program ends. Static variables at namespace scope are initialized when the namespace is loaded and are destroyed when the namespace is unloaded. Static variables in classes are initialized when the class is first used and are destroyed when the program ends. Static variables in functions are initialized when the function is first called and are destroyed when the function returns.
Static variables can be useful for a variety of purposes, such as:
- Storing global state information: Static variables can be used to store global state information that needs to be accessed by multiple functions in a program.
- Implementing singletons: Static variables can be used to implement singletons, which are classes that can only have one instance.
- Implementing lazy initialization: Static variables can be used to implement lazy initialization, which is a technique for delaying the initialization of a variable until it is first used.
Here is an example of a static variable declared in a function:
#include <iostream> using namespace std; void fun() { static int x = 0; x++; cout << x << endl; } int main() { fun(); fun(); return 0; }
This code is a C++ program that defines a function called fun()
and then calls it twice from the main()
function. The fun()
function declares a static variable called x
and increments it each time it is called. The function then prints the value of x
to the console.
Because x
is a static variable, its value is preserved between function calls. This means that when the fun()
function is called the second time, the value of x
will be 1, not 0. Therefore, the output of the program will be as follows:
1 2
This code demonstrates how static variables can be used to store state information that needs to be accessed by multiple function calls.