c语言static的作用
2015-11-17 14:11
344 查看
1、全局变量前的static作用:限制该全局变量的作用域到本文件结束。
例如:下面3个文件,f1.cpp中的全局变量只能在f1.cpp中使用;f2.cpp使用的是f3.cpp中定义的全局变量a。
2、局部变量前的static:定义了静态局部变量,该语句只执行一次,以后使用上一次的结果。
运行结果:
ok1
a=5
ok2
a=6
例如:下面3个文件,f1.cpp中的全局变量只能在f1.cpp中使用;f2.cpp使用的是f3.cpp中定义的全局变量a。
//文件f1.cpp #include "stdio.h" static int a=1; //限定a的作用域:从这里到本文件结束 void f2(); void f3(); void main() { printf("f1中的a=%d\n",a); f2(); f3(); } //文件f2.cpp #include <stdio.h> extern int a; //使用外部全局变量a,即f3.cpp中的全局变量a void f2() { printf("f2中的a=%d\n",a); } //文件f3.cpp #include <stdio.h> int a=3; void f3() { printf("f3中的a=%d\n",a); } 运行结果: f1中的a=1 f2中的a=3 f3中的a=3
2、局部变量前的static:定义了静态局部变量,该语句只执行一次,以后使用上一次的结果。
#include "stdio.h" void f(int b) { static int a=b; printf("a=%d\n",a); a++; } void main() { int m=5; printf("ok1\n"); f(m); printf("ok2\n"); f(m); }
运行结果:
ok1
a=5
ok2
a=6