C 声明:K& ;;R
我正在阅读K&R编写的C编程语言第2章“类型、运算符和表达式”,第2.4节,其中我发现了以下陈述: 如果所讨论的变量不是自动的,则初始化是无效的 仅在程序开始执行之前执行一次,并且 初始值设定项必须是常量表达式。显式 每次函数初始化时,初始化的自动变量都会初始化 或输入其所在的块;初始值设定项可以是任何表达式C 声明:K& ;;R,c,variables,C,Variables,我正在阅读K&R编写的C编程语言第2章“类型、运算符和表达式”,第2.4节,其中我发现了以下陈述: 如果所讨论的变量不是自动的,则初始化是无效的 仅在程序开始执行之前执行一次,并且 初始值设定项必须是常量表达式。显式 每次函数初始化时,初始化的自动变量都会初始化 或输入其所在的块;初始值设定项可以是任何表达式 上面的几行不太清楚它们是什么意思?一个自动变量是一个正常变量。这些变量是在堆栈上创建的,并且每次通过都会初始化。例如: int example_auto(){ int foo =
上面的几行不太清楚它们是什么意思?一个自动变量是一个正常变量。这些变量是在堆栈上创建的,并且每次通过都会初始化。例如:
int example_auto(){
int foo = 0;
foo++;
return foo;
}
int example_static(){
static int foo = 0;
foo++;
return foo;
}
每次调用example\u auto()
时,foo
被初始化为0
。该函数始终返回1
静态变量是用静态
声明的变量,或作为全局变量(在任何函数之外)声明的变量。与自动变量不同,这些变量在程序启动时(或接近启动时)初始化一次。例如:
int example_auto(){
int foo = 0;
foo++;
return foo;
}
int example_static(){
static int foo = 0;
foo++;
return foo;
}
foo
初始化一次example_static()
第一次调用时返回1,然后返回2,然后返回3,以此类推
int a = 5;
int b = a; //error, a is not a constant expression
int main(void)
{
static int c = a; //error, a is not a constant expression
int d = a; //okay, a don't have to be a constant expression
return 0;
}
只有
d
是自动变量,因此只有d
才允许使用其他变量初始化。在C-块中,可以定义两种局部变量:静态和自动。请注意,local only表示变量仅在函数内部可见
然后,每次调用函数/块时都会重新创建一个自动变量,并在控件退出函数/块时销毁该变量。然后在每次创建时对其进行初始化
静态局部变量在程序的整个生命周期中只创建一次。它被销毁,程序结束。并且在创建的同时对其进行初始化:仅在程序开始时初始化一次(概念上可能略有不同)。每次输入函数或块时,都会初始化显式初始化的自动变量:
除了其他答案外,自动(顾名思义)还与运行时处理变量的方式有关。i、 e.在其定义的逻辑块内,其寿命将在进入和离开时自动创建和销毁。无需显式创建或销毁内存,因为每次输入和退出逻辑块(由{…}
定义)时都会这样做。因此,术语“自动”
初始值设定项可以是任何表达式
可以使用其他先前初始化的变量、常量或表达式初始化自动变量
#define MAX 20.0
float d;
int func(void)
{
int a = 10; //automatic
int b = a + 3; //automatic
float c = MAX; //automatic
d = MAX; //d is a file global, not automatic,
//memory created outside of local scope,
//memory is not de-allocated when function exits
static int e = 0; //Not automatic as static gives local variables life
//beyond the function, i.e. outside scope of {...}
//memory, and value of e remain when function exits
//and between calls
return 0;
}
这表明局部变量(也称为自动变量)可以通过常量或非常量表达式初始化-
int a = 5;
int main()
{
int c = a; // local or automatic variable initialized by a non
constant variable
}
但是外部变量也称为全局变量,静态变量不能由非常量变量初始化
int a = 3
int b = a // cannot be initialized by non constant variable
int main()
{
static int d;
d = a // cannot be initialized by a non constant variable
}
它还指出,每当编译器运行自动变量或局部变量所在的代码块时,它们都会重新初始化。因为每次进入代码块时,编译器都会自动分配和取消分配变量的内存位置
void abc(void);// function parameter
int main()
{
abc();
abc();
}
void abc()
{
int i = 0;// automatic variable i is re-intialized every time abc is called
static x = 0; //static variable retains its value
i ++ ;
x ++;
printf("%d\n",i );
printf("%d\n",x );
}
产出-1 2