C语言进阶_变量属性

  人们总说时间会改变一些,但实际上这一切还得你自己来。

一.概念详解

  变量:计算机语言中储存计算结果,其值可以被修改。通过变量名来访问计算机中一段连续的内存空间。

  属性:区别于同类事物的特征。

  C语言中变量的属性关键字有:auto register static extern

二.属性关键字详解

  ①auto

    用于修饰局部变量的默认属性修饰关键字,表明将自动变量表明存储在中。

     @note:auto只能修饰局部变量,修饰全局变量会报错。

 

 1 #include <stdio.h>
 2 auto int var=1;  //err: auto不能修饰全局变量。
 3 int main(){
 4     printf("%d\n",var);
 5     return 0;
 6 }

  ②register

    用于向编译器申请局部变量放入寄存器区域,不一定请求成功。

1 #include <stdio.h>
2 register int var=1;   //err:  register name not specified for 'var'
3 int main(){
4     register int i=1;
5     printf("%d\n",&i); //err:address of register variable 'i' requested
6     printf("%d\n",var);
7     return 0;
8 }

    @note:不能利用取地址运算符&,来获得寄存器变量的地址。

  ③static

    将变量存储到静态区域。

    修饰全局变量:将静态全局变量的作用域缩小到定义文件。

    修饰局部变量:将静态局部变量存储到静态区域,延长局部变量的生命周期。

    修饰函数:静态函数作用域只是声明的文件中。

 1 #include <stdio.h>
 2 int f1(){
 3     int i=0;
 4     i++;
 5     return i;
 6 }
 7 int f2(){
 8     static int i=0;
 9     i++;
10   //k++;      //err:'k' undeclared (first use in this function)
11     return i;
12 }
13 int main(){
14     int j=0;
15     static int k;
16 for(j=0;j<5;j++)
17     printf("%d\n",f1());
18 for(j=0;j<5;j++)
19     printf("%d\n",f2());
20     return 0;
21 }

    

   ④extern

   用于声明外部的变量或函数,告知编译器在其他文件中寻找该变量或函数定义。

     扩展:C与C++语言之间的桥梁,告知C/C++编译器以C语言编译方式编译。

  

1 #include <stdio.h>
2 extern int i;  //
3 int main(){
4     printf("%d\n",i); //告诉编译器i在其他地方可以找到。
5     return 0;
6 }
7 int i=99;

三、extern和static的互斥关系

 extern用于引用外部的,也即其他文件中的全局变量或函数。而static修饰的全局变量作用域被限定在本文件内,故而使用extern关键字引用其他文件的静态全局变量是不行的。

test1.c

1 #include <stdio.h>
2 extern int i;
3 int main(void){
4     printf("%d\n",i);
5     return 0;
6 }

test2.c

 1 #include <stdio.h> 2 static int i=99; 

报错err:undefined reference to `i'

extern可与static结合使用,屏蔽test2代码中的实现细节,只提供一个函数接口给其他人使用,可有效防止泄密。

使用示例:

 1 #include <stdio.h>
 2 extern int getI();
 3 extern int putI(int j);
 4 int main(void){
 5     int i;
 6     i=getI();
 7     printf("%d\n",i);
 8     scanf("%d",&i);
 9     putI(i);
10     i=getI();
11     printf("%d\n",i);
12     return 0;
13 }
 1 #include <stdio.h>
 2 static int i=99;
 3 int getI(){
 4     
 5     return i;
 6 }
 7 int putI(int j){
 8     i=j;
 9     return 0;
10 }

猜你喜欢

转载自www.cnblogs.com/geekj/p/12405143.html
今日推荐