C语言的五种存储类

五种存储类

C Primer Plus 第十二章 存储类、链接和内存管理

存储类 时期 作用域 链接 声明方式
自动 自动 代码块 代码块内
寄存器 自动 代码块 代码块内,使用关键字register
具有外部连接的静态 静态 文件 外部 所有函数之外
具有内部连接的静态 静态 文件 内部 所有函数之外,使用关键字static
空连接的静态 静态 代码块 代码块内,使用关键字static

自动变量

自动变量n,m,i

int loop(int n)
{
    int m; // m 的作用域
    scanf("%d", &m);
    {
            int i; // m 和 i 的作用域
            for (i = m; i < n; i++)
            puts("i is local to a sub-block\n");
    }
    return m; // m 的作用域, i 已经消失
}

寄存器变量

这里写代码片

具有外部链接的静态变量


int Errupt;         /* 外部定义的变量 */
double Up[100];     /* 外部定义的数组 */
extern char Coal;   /* 如果Coal被定义在另一个文件, */
                    /*则必须这样声明*/
void next(void);
int main(void)
{
    extern int Errupt;  /* 可选的声明*/  //引用声明
    extern double Up[]; /* 可选的声明*/
    ...
}
void next(void)
{
    ...
}

具有内部链接的静态变量

int traveler = 1; // 外部链接
static int stayhome = 1; // 内部链接
int main()
{
extern int traveler; // 使用定义在别处的 traveler
extern int stayhome; // 使用定义在别处的 stayhome
...

具有代码块作用域的静态变量

局部静态变量stay

/* loc_stat.c -- 使用局部静态变量 */
#include <stdio.h>
void trystat(void);
int main(void)
{
    int count;
    for (count = 1; count <= 3; count++)
    {
    printf("Here comes iteration %d:\n", count);
    trystat();
    }
    return 0;
}
void trystat(void)
{
int fade = 1;
static int stay = 1;
printf("fade = %d and stay = %d\n", fade++, stay++);
}
注意, trystat()函数先打印再递增变量的值。
 该程序的输出如下:
Here comes iteration 1:
fade = 1 and stay = 1
Here comes iteration 2:
fade = 1 and stay = 2
Here comes iteration 3:
fade = 1 and stay = 3

自动变量:如果未初始化外部变量,别指望这个值是0。可以用非常量表达式 初始化自动变量

int rance = 5 * ruth; // 使用之前定义的变量

外部变量:如果未初始化外部变量, 它们会被自动初始化为 0。与自动变量的情况不同, 只能使用常量表
达式初始化文件作用域变量

int x = 10; // 没问题, 10是常量
int y = 3 + 20; // 没问题, 用于初始化的是常量表达
式
size_t z = sizeof(int); //没问题, 用于初始化的是常量表达式
int x2 = 2 * x; // 不行, x是变量

猜你喜欢

转载自blog.csdn.net/ngany/article/details/76571965