1. Hide
When we compile multiple files, all global variables and functions that do not have a static prefix are globally visible and other source files can be accessed. For example, we have the source file Source1.cpp defines a global variable i and function func
1 source1.cpp 2 int i = 0 3 void Func () 5 { 6 printf ( " hello world\n " 7 }
If I and Func can be referenced in another file main.cpp. However, if a file is to use a variable or function defined in another source file, be sure to include the declaration of the corresponding variable or function in this file. The variables must be declared with extern, and the declaration of the function is not affected by the addition of extern. is as follows:
1 //Source1.cpp2 extern intI//declaration of the variable i3 voidFunc ();//declaration of a function4 5 intMain ()6 {7printf"%d\n", i);//using the variable i8Func ();//use function func ()9 Ten return 0; One}
If the static prefix is added, it cannot be used by other programs like the program above.
1 Static int 0 ; 2 3 Static void Func () 4 {5 printf ("Hello world\n"); 6 }
2. The second effect of static is initialized to 0 by default, including uninitialized global variables and local static variables. In fact, the uninitialized global variable also has this property because the uninitialized global variable is stored in the same area as the uninitialized static variable (BSS segment)
3. The third function of static is to keep the contents of local variables persistent.
The automatic variable inside the function disappears when the function is called, but while the static local variable is defined within the function, the static local variable is always present, that is, its declaration period is the whole source program, which is characterized by only one initialization and the rejection of ' memory '.
The lifetime of a static local variable is the entire source program, but its scope is still the same as the local variable-that is, the variable can only be used within the function that defines it. After exiting the function, you cannot continue to use it even though the variable continues to exist.
"C + +" static explanation