static存储类型可以用于全部变量,无需考虑变量声明的位置。但是作用于块外部和块内部时具有不同的作用。
(1)当作用于函数内部时,和每次程序离开所在块就会丢失值的自动变量不同,static变量会保存下去,块内的static变量只会在程序执行前进行一次初始化,而自动变量则会每次都初始化。接下来对此特性进行验证。
1 #include "stdio.h" 2 void test(void) 3 { 4 static int a = 10; 5 int b = 10; 6 printf("a = %d,b = %dn",a,b); 7 a = 20; 8 b = 20; 9 printf("a = %d,b = %dn",a,b); 10 a = 30; 11 b = 30; 12 printf("a = %d,b = %dn",a,b); 13 printf("***************n"); 14 } 15 void main() 16 { 17 test(); 18 test(); 19 }
test()函数中初始化了两个变量,static变量a和自动变量b,第一次调用完成后结果都是一样的,但是在完成第二次的调用以后,不同的结果出现了,a=30,这就是在上次调用完成之后初始化的30,退出函数后并不会丢失,再次调用函数时也不会初始化,只有在赋值的时候才会改变。
(2)当作用于函数头时。此时的函数只在当前文件有效,对于其他文件不可见。验证程序如下:
test.c
1 /*test.c*/ 2 #include "test.h" 3 #include "stdio.h" 4 static int a = 10; 5 static void test_a() 6 { 7 printf("a = %dn",a); 8 } 9 void put() 10 { 11 test_a(); 12 }
test.h
1 /*test.h*/ 2 #ifndef __TEST_H__ 3 #define __TEST_H__ 4 void put(); 5 static void test_a(); 6 #endif
main.c
1 #include "stdio.h" 2 #include "test.h" 3 void main() 4 { 5 put(); 6 test_a(); 7 }
运行之后发生了如下的错误:
1>c:usersadministratordesktop2017121220171212012017121201main.c(9): error C2129: 静态函数“void test_a()”已声明但未定义
1> c:usersadministratordesktop2017121220171212012017121201test.h(6) : 参见“test_a”的声明
由此可见,static在函数头上时只能在当前文件有效。
内容来源于网络如有侵权请私信删除
- 还没有人评论,欢迎说说您的想法!