#include <stdio.h>
void foo(){int a = 10;static int sa = 10;
a += 5;sa += 5;
printf("a = %d, sa = %d\n", a, sa);}
int main(){int i;
for (i = 0; i < 10; ++i)foo();}
此打印:
a = 15, sa = 15a = 15, sa = 20a = 15, sa = 25a = 15, sa = 30a = 15, sa = 35a = 15, sa = 40a = 15, sa = 45a = 15, sa = 50a = 15, sa = 55a = 15, sa = 60
void foo (){static int i = 0;printf("%d", i); i++}
Another use of static is when you implement a function or global variable in a .c file but don't want its symbol to be visible outside of the .obj generated by the file. e.g.
#include <stdio.h>
/*Undefined behavior: already defined in main.Binutils 2.24 gives an error and refuses to link.https://stackoverflow.com/questions/27667277/why-does-borland-compile-with-multiple-definitions-of-same-object-in-different-c*//*int i = 0;*/
/* Works in GCC as an extension: https://stackoverflow.com/a/3692486/895245 *//*int i;*/
/* OK: extern. Will use the one in main. */extern int i;
/* OK: only visible to this file. */static int si = 0;
void a() {i++;si++;puts("a()");printf("i = %d\n", i);printf("si = %d\n", si);puts("");}
main. c
#include <stdio.h>
int i = 0;static int si = 0;
void a();
void m() {i++;si++;puts("m()");printf("i = %d\n", i);printf("si = %d\n", si);puts("");}
int main() {m();m();a();a();return 0;}
void func(void) {static int count; // If you don't declare its value, it is initialized with zeroprintf("%d, ", count);++count;}
int main(void) {while(true) {func();}return 0;}