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
复制代码

 。

 

posted @   小鲨鱼2018  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!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系统中磁盘容量配额
点击右上角即可分享
微信分享提示