一、C语言变量具有自己的属性
- auto
- static
- register
1.auto
自动变量也称局部变量。将不在任何类、结构、枚举、联合和函数中定义的变量视为全局变量,而在函数中定义的变量视为局部变量。所有局部变量默认都是auto,一般省略不写。
auto声明全局变量时,编译出错:
auto int i;
void main(void)
{
}
auto声明局部变量时,编译正常:
void fun(auto int i)
{
auto int j = i;
}
void main(void)
{
auto int i = 1;
fun(i);
}
-
static
static关键字指明变量的“静态”属性
static关键同时具有“作用域限定符”的意义
static修饰的局部变量存储在程序静态区,每次访问的时候会拿上一次的值
static的另一个意义是文件作用域标示符
―static修饰的全局变量作用域只是声明的文件中
―static修饰的函数作用域只是声明的文件中 -
register
register关键字指明将变量存储于寄存器中
register只是请求寄存器变量,但不一定请求成功 ,但不一定请求成功
register变量的必须是CPU寄存器可以接受的值
因为register变量可能不存放在内存中,所以不能用“&”来获取register变量的地址。
void main()
{
register int a = 0;
int *p = &a; //错误
}
只有局部自动变量和形式参数可以作为寄存器变量,其它(如全局变量、结构体、共用体内部变量)不行。特别地,静态局部变量不能定义为寄存器变量。
struct _STRUCT_NAME_
{
register int a; //错误
};
union _UNION_NAME_
{
register int b; //错误
};
register int c; //错误
void main()
{
register static int d = 0; //错误
}
二、代码测试auto、static、register
#include <stdio.h>
void test_auto()
{
auto int a = 0;
int b = 1;
printf("auto a = %d, b = %d\n", a, b);
}
void test_static()
{
static int a = 0;
int b = 0;
a++;
b++;
printf("static a = %d, b = %d\n", a, b);
}
void test_register()
{
register int a = 0;
int b = 0;
printf("register a addr = 0x%x, b addr = 0x%x\n", &a, &b); //这里取register b的地址没有报错,可能申明不成功
}
int main()
{
test_auto();
test_static();
test_static();
test_register();
return 0;
}
可以看到运行结果:
申明了static的变量第二次访问的时候取得是上一次的值