总结C中关于存储的几个关键字,
*基本概念
---作用域,
一个标识符能产生作用的区域,如变量的作用域可以是代码块作用域,函数原型作用域,文件作用域.
---链接
说明一个标识符的可以被使用的范围.分为外部链接(external linkage),内部链接(internal linkage),空链接(no linkage).
如,代码块作用域和函数原型作用域具有no linkage,文件作用域具有external或internal linkage.
---存储时期,
定义了变量的生命周期.分类:
静态存储时期(static storage duration),在程序运行时期,一直存在的变量.如文件作用域的变量就是静态存储时期.
自动存储时期(automatic storage duration),如函数结束时,他内部的变量占用的内存被释放给其他变量使用
*存储类
---根据作用域,链接和存储其定义了5种存储类,如下图
*自动变量
---可以使用关键字auto显示声明,一般代码块和函数头定义的变量就自动变量
---不显示声明自动变量,则不会自动初始化
---内部变量覆盖外部变量的问题,如下
1 #include <stdio.h> 2 3 int main(void){ 4 int i = 1; 5 for(int i=0;i<6;i++){ 6 printf("internal i: %d\n",i); 7 } 8 printf("external i: %d\n",i); 9 10 return 0; 11 } /* dzh@dzh-laptop:~/lx/c$ gcc -std=c99 test_auto.c dzh@dzh-laptop:~/lx/c$ ./a.out internal i: 0 internal i: 1 internal i: 2 internal i: 3 internal i: 4 internal i: 5 external i: 1 */
例子说明2点,一是c99中for循环部分被看做代码块,二是作用域内同名变量时,代码块内变量优先级更加高.
*寄存器变量
---关键在register
---普通变量分配在内存中,寄存器变量可能被分配到CPU的寄存器或者高速的内存,这类变量的操作速度就更加快了.
---注意,
1)无法对寄存器变量使用&操作获取地址
2)只能用于部分类型,比如说寄存器可能无法容纳double类型
*代码块作用域的静态变量
---变量的可见范围是代码块内,但是他的值会一直保留至程序结束
---示例
1 #include <stdio.h> 2 3 void test_stat(int); 4 5 int main(void){ 6 int i; 7 for(i=0;i<6;i++){ 8 test_stat(i); 9 } 10 11 return 0; 12 } 13 14 void test_stat(int i){ 15 printf("When i = %d\n",i); 16 static int stat = 1; 17 int j; 18 for(j=0;j<=i;j++){ 19 printf("The stat value: %d\t",stat); 20 ++stat; 21 } 22 printf("\n"); 23 } /* When i = 0 The stat value: 1 When i = 1 The stat value: 2 The stat value: 3 When i = 2 The stat value: 4 The stat value: 5 The stat value: 6 When i = 3 The stat value: 7 The stat value: 8 The stat value: 9 The stat value: 10 When i = 4 The stat value: 11 The stat value: 12 The stat value: 13 The stat value: 14 The stat value: 15 When i = 5 The stat value: 16 The stat value: 17 The stat value: 18 The stat value: 19 The stat value: 20 The stat value: 21 */
*外部链接的静态变量
---定义方式:
在所有函数定义外定义的外部变量;
或者在函数内,显示声明关键字extern(表示引用关系);
---注意
1)默认初始化值为0(静态变量的特性,声明时即被创建),只能使用常量表达式初始化;
2)extern int i = 1的写法是错误的,因为extern表示这个变量引用自其它的地方,变量在最初声明时被初始化.
*内部链接的静态变量
---定义:
static修饰的在所有函数之外声明的变量
---与外部链接静态变量的区别
1)作用域,内部的只能在定义的文件内被使用;外部的可以被任何其它文件引用.
---示例
1 #include <stdio.h> 2 3 extern int ext1; 4 5 void extern1(void){ 6 ext1++; 7 }
1 #include <stdio.h> 2 3 void test_ext(void); 4 5 int ext1 = 1; //外部链接的静态 6 static int ext2; //内部链接的静态 7 8 int main(void){ 9 extern int ext1,ext2; 10 ext2 = 1; 11 test_ext(); 12 13 extern1(); 14 printf("extern ext1: %d\n",ext1); 15 16 return 0; 17 } 18 19 void test_ext(void){ 20 int ext1 = 0; 21 extern int ext2; 22 23 printf("auto ext1: %d\n",ext1); 24 printf("extern ext2: %d\n",++ext2); 25 } /* auto ext1: 0 extern ext2: 2 extern ext1: 2 */