c语言中作用域和存储期

 

001、作用域:快作用域,文件作用域; 指的是变量的作用范围; 作用域控制的是变量的作用范围

如下程序:

复制代码
[root@localhost test]# ls
test.c
[root@localhost test]# cat test.c         ## 测试c程序
#include <stdio.h>

int a = 100;                       ## 文件作用域

int main(void)
{
        int a = 500;               ## 块作用域可见
        printf("a = %d\n", a);

        int b = 200;              ## 外层块作用域
        int i;
        for(i = 1; i <= 1; i++)
        {
                int b = 700;      ## 内层块作用域 可见, 具有块作用域的变量,其作用范围只在程序块中
                printf("b1 = %d\n", b);
        }
        printf("b2 = %d\n", b);       ## 此处的变量是b = 200的变量

        return 0;
}
[root@localhost test]# gcc test.c -o kkk
[root@localhost test]# ls
kkk  test.c
[root@localhost test]# ./kkk
a = 500
b1 = 700
b2 = 200
复制代码

 。

 

002、存储期:自动存储期,静态存储期; 存储期控制的是变量的生存期(是在一个程序块内,还是整个程序的结束)。

如下程序:

复制代码
[root@PC1 test]# ls
test.c
[root@PC1 test]# cat test.c       ## 测试程序
#include <stdio.h>
int fx = 0;                       ## 在程序快外声明的变量,具有静态存储期
void func(void)
{
        static int sx = 0;        ## 使用关键字static声明的变量, 具有静态存储int ax = 0;               ## 具有自动存储期
        printf("%3d%3d%3d\n", fx++, ax++, sx++);
}
int main(void)
{
        int i;
        puts(" ax sx fx ");
        for(i = 0; i < 5; i++)    ## 函数连续调用了5次,具有自动存储期的变量在一个程序快结束时,变量消失,如ax,每次调用都为0; 
        {                         ## 而具有静态存储期的变量fx和sx,在程序结束前都可见,因此逐次递增
                func(); 
        }
        return 0;
}
[root@PC1 test]# gcc test.c -o kkk
[root@PC1 test]# ls
kkk  test.c
[root@PC1 test]# ./kkk
 ax sx fx
  0  0  0
  1  0  1
  2  0  2
  3  0  3
  4  0  4
复制代码

 。

 

posted @   小鲨鱼2018  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2023-11-21 如何在word方框内打v_如何在word方框内打v
2021-11-21 R语言中which函数的简单用法,主要用于返回指定条件项的索引
2021-11-21 linux 系统中sed预存储技术 示例
2021-11-21 正则表达式通配符 + 和 * 的区别
2021-11-21 linux系统中同时提取多个文件的前几行并合并为新文件
2021-11-21 linux系统中添加空行
2021-11-21 linux系统中正则表达式记录
点击右上角即可分享
微信分享提示