如果一个变量变static修饰,会产生什么样的结果?(1)static修饰局部变量:例如:运行结果为:#include <stdio.h> void test() { int a=0;//a为局部变量 a++; printf("%d",a); } int main () { int i=0;//i为局部变量 for(i=0;i<10;i++) { test(); } return 0; }
![]()
当a被static修饰之后:
运行结果为:#include <stdio.h> void test() { static int a=0;//a为局部变量 a++; printf("%d",a); } int main () { int i=0;//i为局部变量 for(i=0;i<10;i++) { test(); } return 0; }
即static修饰一个普通的局部变量改变了这个变量的生命周期,这个变量的生命周期和程序的生命周期相同,直到程序结束才销毁。
(2)static修饰全局变量:
在VS中新建一个项目,添加两个源文件,分别命名为1.c和2.c,
#include <stdio.h>//源文件1.c中的代码 int a = 2018;//a为全局变量 #include <stdio.h>//源文件2.c中的代码 extern int a; int main() { printf("%d\n", a); return 0; }
运行结果为:
当a被static修饰后:
#include <stdio.h>//源文件1.c中的代码 int a = 2018;//a为全局变量 #include <stdio.h>//源文件2.c中的代码 extern int a; int main() { printf("%d\n", a); return 0; }
在调试过程中出现了错误:1.无法解析的外部命令。2.无法解析的外部符号a。
#include <stdio.h>//源文件1.c中的代码 static int a = 2018; void test() { printf("test a=%d", a); } #include <stdio.h>//源文件2.c中的代码 extern void test(); int main() { test (); return 0; }
此时运行结果为:
即static修饰全局变量
1.使得这个全局变量只能在当前源文件内使用,不能在其他源文件使用。
2.改变了全局变量的作用域。