There are two uses for the static of C + +: Static in process programming and static in object oriented programming. The former is applied to ordinary variables and functions and does not involve classes; the latter mainly describes the role of static in class.
Static in process-oriented design
1. Static Global variables
The variable is defined as a static global variable before the global variable, plus the keyword static. Let's first give an example of a static global variable, as follows:
//Example 1
#include <iostream.h>
void fn();
static int n; //定义静态全局变量
void main()
{
n=20;
cout<<n<<endl;
fn();
}
void fn()
{
n++;
cout<<n<<endl;
}
Static global variables have the following characteristics:
The variable allocates memory in the global data area;
Uninitialized static global variables are automatically initialized by the program to 0 (the value of the automatic variable is random unless it is explicitly initialized);
A static global variable is visible to the entire file in which it is declared, but not to the file; Static variables allocate memory in the global data area, including the static local variables to be mentioned later. For a complete program, the distribution in memory is shown below:
Code Area |
Global Data area |
Heap Area |
Stack area |
The dynamic data generated by new in general program is stored in the heap area, and the automatic variables inside the function are stored in the stack area. Automatic variables typically release space as the function exits, and static data (even static local variables within the function) is stored in the global data area. The data in the global data area does not free up space because of the exit of the function. Attentive readers may find that the code in Example 1 will
static int n; //定义静态全局变量
To
int n; //定义全局变量
The program still works.