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 @ 2024-11-21 14:49  小鲨鱼2018  阅读(18)  评论(0)    收藏  举报