The keyword static can be used in three major contexts: inside a function, inside a class definition, and in front of a global variable inside a file making up a multifile program.
The use of static inside a function is the simplest. It simply means that once the variable has been initialized, it remains in memory until the end of the program. You can think of it as saying that the variable sticks around, maintaining its value, until the program completely ends. For instance, you can use a static variable to record the number of times a function has been called simply by including the lines static int count =0; and count++; inside the function. Because count is a static variable, the line “static int count = 0;” will only be executed once. Whenever the function is called, count will have the last value assigned to it.
1 2 3 4 5 6 7 8 | for(int x=0; x<10; x++) { for(int y=0; y<10; y++) { static int number_of_times = 0; number_of_times++; } } |
The second use of static is inside a class definition. While most variables declared inside a class occur on an instance-by-instance basis (which is to say that for each instance of a class, the variable can have a different value), a static member variable has the same value in any instance of the class and doesn’t even require an instance of the class to exist.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class user { private: int id; static int next_id; public: static int next_user_id() { next_id++; return next_id; } /* More stuff for the class user */ user() { id = user::next_id++; //or, id = user.next_user_id(); } }; int user::next_id = 0; |
You can also have static member functions of a class. Static member functions are functions that do not require an instance of the class, and are called the same way you access static member variables — with the class name rather than a variable name. (E.g. a_class::static_function(); rather than an_instance.function();) Static member functions can only operate on static members, as they do not belong to specific instances of a class.