I. Prerequisites
Titles by scope and location
Local variable: variable defined in the function <----> internal variable
Global variables: variables defined outside the function <----> external variables
Variable category:
| ------- Scope: local variable; global variable
| ------- Life cycle: dynamic variable; static variable
Ii. Similarities (three functions)
In C, the static keyword has the following three functions. These three functions are also applicable to C ++.
1. declare static local variables
Understanding: Set the life cycle of a local variable to the life cycle of the entire application.
However, this does not affect that its scope is still partial.
Case:
In the TestStaticLocalVariable () function, a is a local variable and declared as a static type.
Therefore, when TestStaticLocalVariable () is called for the first time, a is assigned an initial value of 1 and 2 is output;
The second is that when TestStaticLocalVariable () function is called, The Definition Statement of a is skipped and a ++ is directly executed. Because a saves 2, all ++ is output 3.
2. declare static external variables
Understanding:This is an external variable declared as static.
To prevent external variables defined in this file from being used by other files.
Note: external variables must be static storage (Life Cycle), Whether static or not.
However, after static is addedScopeIt changes.
Case:
(1) create a new C ++ Project and add a cpp File named File. Add the following code:
(2) Declare external variables in the main. cpp file and try to use them.
It can be seen that the compiler reports an error to stc, while var can pass. Because, stc is declared as static.
3. Declare internal functions
Internal functions: functions that cannot be called by other files
External functions: functions that can be called by other files
Understanding:Similar to external variables.
Functions defined in this file cannot be used by other files.
Case:
(1) create a new C ++ Project and add a cpp File named File. Add the following code:
(2) Declare the add and sub external functions in the main. cpp file and try to use them.
It can be seen that the compiler will add an error, while sub can pass. Because the add function is declared as the static type, which cannot be used in mian. cpp.
Iii. Differences (Class Members)
This is different from the static usage of C ++.
1. static member variables and static member functions of the class
In this regard, I will not mention it much.
Remember that static member variables and functions can only be referenced by class names, but cannot be referenced by class objects.
See my other blog: http://blog.csdn.net/jarvischu/article/details/6420184