mch*_*mch 11
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;
}
Run Code Online (Sandbox Code Playgroud)
只是d一个自动变量,因此只d允许用其他变量初始化.
自动变量是普通变量。这些变量在堆栈上创建并每次都进行初始化。例如:
int example_auto(){
int foo = 0;
foo++;
return foo;
}
Run Code Online (Sandbox Code Playgroud)
foo0每次调用时都会初始化example_auto()。该函数始终返回 1。
静态变量static是用, 或全局变量(在任何函数之外)声明的变量。与自动变量不同,这些变量在程序启动时(或接近启动时)初始化一次。例如:
int example_static(){
static int foo = 0;
foo++;
return foo;
}
Run Code Online (Sandbox Code Playgroud)
foo被初始化一次。 example_static()第一次调用时返回 1,然后返回 2,然后返回 3,依此类推。