C语言tips:static 修饰符—生命的魔法棒

    科技2022-07-14  117

    static 修饰符—生命的魔法棒

    普通的局部变量static修饰局部变量static修饰全局变量,守卫我的变量 static 英 [ˈstætɪk] 美 [ˈstætɪk] adj. 静止的;静态的;停滞的;静力的 n. 天电(干扰);静电;静力学

    就像它的本意,static作为C语言关键字,主要的作用就是冻结局部变量。局部变量在函数完成使命消亡后,继续存在,延长生命周期,下次继续调用。

    普通的局部变量

    void static_test (int time) { int num = 0;//定义函数内局部变量num,每次调用函数num++。 printf("%d time num value:%d\n",time,num); //参数time,是调用static_test函数的次数。 num++; } int main(int argc, char const* argv[]) { //反复调用static_test函数,查看局部变量num的值的变化。 static_test(1); static_test(2); static_test(3); static_test(4); static_test(5); return 0; } //输出结果,局部变量num的值,没有发生变化。 1 time num value:0 2 time num value:0 3 time num value:0 4 time num value:0 5 time num value:0

    可以看出static_test函数中局部变量num的值,没有发生变化。num的值随着static_test函数的结束一起陪葬(消亡)了。下一次调用static_test函数的时候,再重新给变量num分配空间。所以每次调用static_test函数,num都是新生的变量,值都是0。

    static修饰局部变量

    void static_test (int time) { static int num = 0;//加上static修饰符。 printf("%d time num value:%d\n",time,num); //参数time,是调用static_test函数的次数 num++; } int main(int argc, char const* argv[]) { //反复调用static_test函数,查看局部变量num的值的变化。 static_test(1); static_test(2); static_test(3); static_test(4); static_test(5); return 0; } //输出结果,局部变量num的值,发生变化。 1 time num value:0 2 time num value:1 3 time num value:2 4 time num value:3 5 time num value:4

    可以看出num的值随着static_test函数的调用,依次递增。static关键字延长了num的生命,不会随着函数的结束而陪葬。只定义初始化一次,后面再次调用static_test函数时,会直接使用。但num的作用域没有变化,依旧只能在static_test函数内使用,否则产生报错。

    int main(int argc, char const* argv[]) { //在主函数中直接调用static_test函数中的num变量。 printf("the num value:%d",num); return 0; } //产生报错,使用未声明的变量。 hello.c:9:31: error: use of undeclared identifier 'num' printf("the num value:%d",num); ^ 1 error generated.

    static修饰全局变量,守卫我的变量

    //test.h头文件,连接两个.c源文件。 #ifndef _test_h #define _test_h void test_print(int a); #endif //test.c源文件,实现函数。 #include<stdio.h> static int a = 12;//用static来修饰全局变量。 void test_print(int a) { printf("this is main.c,the a value is :%d\n",a); } //main.c源文件,程序入口。 #include <stdio.h> #include "test.h" int main(int argc, char const* argv[]) { extern int a;//声明变量a是一个外部变量。 printf("this is main.c,the a value is :%d\n",a); test_print(a); return 0; } //产生链接错误。 Undefined symbols for architecture x86_64: "_a", referenced from: _main in hello-dcdf68.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

    可以看出,经过static修饰的全局变量,只能在这个全局变量只能在所定义的文件内使用,其他文件不能使用。当test.c文件中去掉static关键字,就没有问题了。

    this is main.c,the a value is :12 this is test.c,the a value is :12

    Processed: 0.014, SQL: 8