1
2
3
4
5
6
7
8
9
10
11
12
13
int GenerateID()
{
static int s_nID = 0;
return s_nID++;
}
int main()
{
std::cout << GenerateID() << std::endl;
std::cout << GenerateID() << std::endl;
std::cout << GenerateID() << std::endl;
return 0;
This program prints:
Note that s_nID has kept it’s value across multiple function calls.
The static keyword has another meaning when applied to global variables — it changes them from global scope to file scope. Because global variables are typically avoided by competent programmers, and file scope variables are just global variables limited to a single file, the static keyword is typically not used in this capacity.
Static member variables
C++ introduces two new uses for the static keyword when applied to classes: static member variables, and static member classes. Before we go into the static keyword as applied to member variables, first consider the following class: