Static variables
The static
keyword can be placed before the datatype in a variable declaration to create a static variable. Static variables adhere to three rules:
- They are initialized only the first time the declaration is encountered in the program
- They remain in memory after the scope of the variable ends
- Despite remaining in memory, they are still only accessible within the scope of the variable
One use of a static variable is to count the number of times a function has been called as shown below:
void fcn()
{
static int i = 0;
cout << "This function has been called " << ++i << " times." << endl;
}
fcn(); // This function has been called 1 times.
fcn(); // This function has been called 2 times.
fcn(); // This function has been called 3 times.
fcn(); // This function has been called 4 times.
fcn(); // This function has been called 5 times.
The static
keyword has other uses in C++, especially related to classes.