当我在生产线上运行这个程序时,我得到了ERROR
static int b = a; //error : initializer element is not constant不明白为什么?
#include <stdio.h>
// #include <setjmp.h>
int main()
{
int a = 5;
static int b = a;
return 0;
}发布于 2012-06-22 19:28:19
除此处其他答案中所述的其他原因外,请参阅本标准中的以下声明。
C Standard在第-4点(第6.7.8节初始化)中这样说:
All the expressions in an initializer for an object that has static storage duration
shall be constant expressions or string literals.另外,关于什么是常量表达式,它在6.6节常量表达式中如下所述:
A constant expression can be evaluated during translation rather than runtime, and
accordingly may be used in any place that a constant may be.发布于 2012-06-22 19:27:04
在C中(与C++不同),任何具有静态存储持续时间的对象的初始化器-包括函数静态-必须是常量表达式。在您的示例中,a不是常量表达式,因此初始化无效。
C99 6.7.8 / 4:
具有静态存储持续时间的对象的初始值设定项中的所有表达式都应为常量表达式或字符串文字。
发布于 2012-06-22 19:23:56
静态变量始终是全局变量,因为它不在任何线程的堆栈上,并且它的声明是否在函数中并不重要。
因此,全局变量b的初始化是在程序启动期间执行的,在调用任何函数(包括main)之前,即此时不存在a,因为a是局部变量,它在调用函数(这里是main)之后将其内存放在堆栈中。
因此,你真的不能期望编译器接受它。
https://stackoverflow.com/questions/11154957
复制相似问题