变量类型(接C变量作用域,生存期,链接特性)
Posted jeffrey-yang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了变量类型(接C变量作用域,生存期,链接特性)相关的知识,希望对你有一定的参考价值。
自动变量
自动存储类型,特点:自动存储期,块作用域,无链接。默认情况下,在块级作用域中或函数头中的变量属于自动存储类型的变量。当然,也可以受用关键字"auto"特别声明,一般用处不大。
示例:
// hiding.c -- variables in blocks
#include<stdio.h>
int main()
{
int x = 30; // original x
printf("x in outer block: %d at %p
", x, &x);
{
int x = 77; // new x, hides first x
printf("x in inner block: %d at %p
", x, &x);
}
printf("x in outer block: %d at %p
", x, &x);
while (x++ < 33) // original x
{
int x = 100; // new x, hides first x
x++;
printf("x in while loop: %d at %p
", x, &x);
}
printf("x in outer block: %d at %p
", x, &x);
return 0;
}
输出:
x in outer block: 30 at 0x7ffee9725ae8
x in inner block: 77 at 0x7ffee9725ae4
x in outer block: 30 at 0x7ffee9725ae8
x in while loop: 101 at 0x7ffee9725ae0
x in while loop: 101 at 0x7ffee9725ae0
x in while loop: 101 at 0x7ffee9725ae0
x in outer block: 34 at 0x7ffee9725ae8
没有{}的块级作用域
loop或if内的代码一般也会产生一个块,其中定义的变量的生存期只在loop内或条件判断内。
示例:
// forc99.c -- new C99 block rules
#include<stdio.h>
int main()
{
int n = 8;
printf(" Initially, n = %d at %p
", n, &n);
for (int n = 1; n < 3; n++)
printf(" loop 1: n = %d at %p
", n, &n);
printf("After loop 1, n = %d at %p
", n, &n);
for (int n = 1; n < 3; n++)
{
printf(" loop 2 index n = %d at %p
", n, &n);
int n = 6;
printf(" loop 2: n = %d at %p
", n, &n);
n++;
}
printf("After loop 2, n = %d at %p
", n, &n);
return 0;
}
输出:
Initially, n = 8 at 0x7ffeef08dae8
loop 1: n = 1 at 0x7ffeef08dae4
loop 1: n = 2 at 0x7ffeef08dae4
After loop 1, n = 8 at 0x7ffeef08dae8
loop 2 index n = 1 at 0x7ffeef08dae0
loop 2: n = 6 at 0x7ffeef08dadc
loop 2 index n = 2 at 0x7ffeef08dae0
loop 2: n = 6 at 0x7ffeef08dadc
After loop 2, n = 8 at 0x7ffeef08dae8
寄存器变量
在块级作用域内使用关键字"register",和自动变量的唯一区别是该变量保存在CPU寄存器中,而不是内存中,意味着不能进行取地址操作(指针等)。寄存器变量存储在CPU寄存器中,可以比常规变量更快地访问和操作。不过编译器会权衡可用寄存器的数量和你的显式寄存器变量声明,因此有可能会忽略该声明,从而该变量实际上会变为自动变量,但仍然不能使用地址操作符进行操作。
块级作用域中的静态变量
特点:作用域为块级,存储期为静态存储期,无链接。
示例:
// loc_stat.c using a local static variable
#include<stdio.h>
void trystat(void);
int main(void)
{
int count;
for (count = 1; count <= 3; count++)
{
printf("Here comes iteration %d:
", count);
trystat();
}
return 0;
}
void trystat(void)
{
int fade = 1;
static int stay = 1;
printf("fade = %d and stay = %d
", fade++, stay++);
}
输出:
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
说明:虽然静态变量stay在trystat函数中声明,但该变量只会声明一次,这是因为静态变量和外部变量在程序加载到内存前已经存在。将静态变量的声明放在函数内只是为了告诉编译器该变量仅在该函数内可见。
以上是关于变量类型(接C变量作用域,生存期,链接特性)的主要内容,如果未能解决你的问题,请参考以下文章