c语言中存储期概念、自动存储期和静态存储期的对比
存储期可以分为两类:自动存储期和静态存储期。
自动存储期:变量的作用周期在程序块内; 在程序块中使用一般的变量声明模式即可。
静态存储期:变量的作用周期在整个程序期间; 有两种声明方式,1、在程序块外声明; 2、在程序块内使用static关键字
001、自动存储期测试
[root@PC1 test]# ls test.c [root@PC1 test]# cat test.c #include <stdio.h> void fun(void) { int x = 100; // 程序块中定义变量,存储期只在程序块内,结束变量消失 printf("x = %d\n", x++); } int main(void) { int i; for(i = 0; i < 3; i++) { fun(); // 对函数连续调用3次,结果都是100;表明程序存储期只在函数的程序块内 } return 0; } [root@PC1 test]# gcc test.c -o kkk ## 编译 [root@PC1 test]# ls kkk test.c [root@PC1 test]# ./kkk ## 测试 x = 100 x = 100 x = 100
。
002、静态存储期(在程序块内使用关键字static)
[root@PC1 test]# ls test.c [root@PC1 test]# cat test.c ## 测试程序 #include <stdio.h> void fun(void) { static int x = 100; // 定义具有静态存储期的变量 printf("x = %d\n", x++); } int main(void) { int i; for(i = 0; i < 3; i++) // 函数来纳许调用3次,x的值一致在增加,说明x的存储期在整个程序的周期 { fun(); } return 0; } [root@PC1 test]# gcc test.c -o kkk ## 编译 [root@PC1 test]# ls kkk test.c [root@PC1 test]# ./kkk ## 测试 x = 100 x = 101 x = 102
。
003、静态存储期(在程序块外定义变量)
[root@PC1 test]# ls test.c [root@PC1 test]# cat test.c #include <stdio.h> int x = 100; // 在程序块外定义变量具有静态存储期 void fun(void) { printf("x = %d\n", x++); } int main(void) { int i; for(i = 0; i < 3; i++) // 连续调用函数三次 { fun(); } return 0; } [root@PC1 test]# gcc test.c -o kkk ## 编译 [root@PC1 test]# ls kkk test.c [root@PC1 test]# ./kkk ## 测试 x = 100 x = 101 x = 102
。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2023-11-09 非root 用户安装perl模块
2023-11-09 Can't locate CPAN.pm in @INC (@INC contains: /usr/local/lib64/perl5
2023-11-09 Warning: prerequisite Test::More 0 not found.
2022-11-09 使用 gff2bed 将 gff文件转换为bed格式
2022-11-09 /usr/bin/ld: cannot find -lm
2022-11-09 File "/usr/bin/yum", line 30
2020-11-09 linux系统中磁盘容量配额