Static keyword usage in C and C ++, static keyword
I. Two methods of using the static keyword in C Language
1) it is used to modify the variable inside the function, that is, the static variable in the function. The lifetime of this variable is longer than this function. Yes, the function has a certain "state". functions using static variables are generally not reentrant, nor thread-safe, such as strtok ()
2) It is used at the file level (in vitro function) to modify a variable or function. The variable or function can only be visible in the text. Other files cannot see it or access the variable or function.
Ii. Four usage of static keywords in C ++
Because C ++ introduces class, while maintaining compatibility with C language, the static keyword has two new usage methods:
3) The user modifies the data member of the class, that is, the so-called "static member". the lifetime of the data member is greater than the object (entity/instance) of the class ), static data members have one copy for each class, and common data members have one copy for each iinstance. Therefore, they are also called class variable and Instance variable.
4) The member function used to modify the class, that is, the so-called "static member function". Such a member function can only access class variable or other static program functions, but cannot access instance variable or instance method.
These usage methods can be combined. For example, a member function of C ++ (both static and instance) can have its local static variables (the preceding usage 1 ). For the class template and function template, the actual number of static objects is related to the template instantiation (the template is made available.