1. First and foremost, the first and most important one: hide.
When we compile multiple files at the same time, all global variables and functions without a static prefix have global visibility. To understand this sentence, I say for example. We want to compile two source files at the same time, one is A.C and the other is main.c.
Here's what the A.C:
char a = 'A'; // global variable
void msg()
{
printf("Hello\n");
}
Here's what the MAIN.C:
int main(void)
{
extern char a; // extern variable must be declared before use
printf("%c ", a);
(void)msg();
return 0;
}
The results of the program's operation are:
A Hello
You might ask: Why is the global variable A and function msg defined in A.C used in MAIN.C? As mentioned earlier, all global variables and functions without a static prefix have global visibility and other source files can be accessed. In this example, a is a global variable, MSG is a function, and neither has a static prefix, so main.c is visible for another source file.
If static is added, the other source files are hidden. For example, add static,main.c to the definition of a and MSG before you can see them. With this feature, you can define a function with the same name and a variable of the same name in different files without worrying about naming conflicts. Static can be used as a prefix for functions and variables, and for a function, static is limited to hiding, and for a variable, static has the following two effects.
The second role of 2.static is to keep variable content persistent.
A variable stored in a static data area completes initialization and is only initialized once the program is first run. There are two variables stored in the static store: Global and static variables, but compared to global variables, static can control the scope of the variable, in the final analysis static or to hide. Although this usage is not common, I would like to cite an example.
#include <stdio.h>
int fun(void){
static int count = 10; // 事实上此赋值语句从来没有执行过
return count--;
}
int count = 1;
int main(void)
{
printf("global\t\tlocal static\n");
for(; count <= 10; ++count)
printf("%d\t\t%d\n", count, fun());
return 0;
}