Static is a keyword in C++ used to give special characteristics to an element. Static elements are allocated storage only once in a program lifetime in static storage area. And they have a scope till the program lifetime. Static keyword can be used with following:
-
Static variable in functions
Static variables when used inside function are initialized only once, and then they hold there value even through function calls.
These static variables are stored on static storage area, not in stack.(《理解static storage area VS. stack In C++》)
void counter() { static int count = 0; cout << count++; } int main () { for (int i=0; i<5; i++) { counter(); } } >>> output 0 1 2 3 4
Sa