作用域:
//首先区分文件作用域和块作用域
//文件作用域需要使用include 头文件,或者extern 引用
//块作用域中的块指的是代码块,以花括号{}为标志
//1.在main函数中,首先调用print_x函数,此时,函数上面的x=700就是块作用域,打印出700
//2.printf函数中,此时的x=800具有块作用域,x=700具有文件作用域,因此打印出800
//3.在for循环中,x变量的块作用域就是for循环的{},因此x=800相对来说就是文件作用域,打印结果 0 100 200 300 400
#include <stdio.h>
int x = 700;
void print_x(void)
{
printf("x=%d/n", x);
}
int main()
{
int i;
int x = 800;
print_x();
printf("x=%d/n", x);
for (i = 0; i < 5; i++)
{
int x = i * 100;
printf("x=%d/n", x);
}
printf("x=%d/n", x);
return 0;
}
存储期:
//ax,fx是静态存储期,每次跳出main函数时,变量本身不会被销毁
//ax为自动存储期,只生存在{}里,每次调用才会激活,使用完后销毁
#include <stdio.h>
int fx;
void func(void)
{
static int sx = 0;
auto int ax = 0;
printf("%3d%3d%3d/n", ax++, sx++, fx++);
}
int main()
{
int i;
puts("ax sx fx");
puts("--------");
for (i = 0; i < 10; i++)
{
func();
}
puts("--------");
return 0;
}
//代码清单6-20
//变量的存储期即是它的寿命,分为两种:自动存储期和静态存储期
//静态存储期:static storage duration,使用static修饰变量
//----------main函数执行之前就初始化,在函数外出现或是被static修饰
//----------该对象默认初始化为0,且在程序结束时候才消失
//自动存储期:auto......,auto修饰(一般省略),生存期限为{}内
//----------int ax =0,初始化ax为0;int ax 初始化为不定值
#include <stdio.h>
int fx;
int main()
{
static int sx;
int ax;
printf("ax = %d/n", ax);//不定值,有些编译器会报错
printf("sx = %d/n", sx);//0
printf("fx = %d/n", fx);//0
return 0;
}
原创文章,作者:kirin,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/277001.html