How is the “static” keyword used in the C language?
In the C language, the static keyword serves two main purposes:
- unmoving
Here is an example:
#include <stdio.h>
void test() {
static int count = 0;
count++;
printf("count: %d\n", count);
}
int main() {
test(); // 输出:count: 1
test(); // 输出:count: 2
test(); // 输出:count: 3
return 0;
}
In the example above, every time the test function is called, the value of count will increase and retain the result from the previous call. This is because count is declared as static, so it does not get destroyed after the function execution.
- unchanging
Here is an example:
// file1.c
#include <stdio.h>
static int count = 0;
void increment() {
count++;
}
void display() {
printf("count: %d\n", count);
}
// file2.c
#include <stdio.h>
extern void increment();
extern void display();
int main() {
increment();
increment();
display(); // 输出:count: 2
return 0;
}
In the above example, count is declared as static, so it can only be accessed in file1.c. In file2.c, the increment and display functions can be declared using the extern keyword, and then called in the main function to manipulate and display the value of count.