7
#include <stdio.h>

int i=10;
int j=i;
int main()
{
    printf("%d",j);
}

我收到一条错误消息,指出初始化元素不是常量?这背后的原因是什么?

4

4 回答 4

12

这背后的原因是什么?

C(与 C++ 不同)不允许使用非常量值初始化全局值。

C99 标准:第 6.7.8 节:

具有静态存储持续时间的对象的初始化程序中的所有表达式都应为常量表达式或字符串文字。

于 2012-12-09T06:28:35.507 回答
2

您可以尝试使用:

int i=10;
int j=0;

int main()
{
   j=i;//This should be the first statement in the main() and you achieve the same functionality as ur code
   return 0;
}

唯一真正的 C 方法是在运行时对其进行初始化。尽管在 C++ 中您的代码可以正常工作,但不会出现任何编译错误。

C 标准明确禁止使用非常量值初始化全局对象。Section 6.7.8C99 标准中说:

具有静态存储持续时间的对象的初始化程序中的所有表达式都应为常量表达式或字符串文字。

对象的定义static storage duration在第 6.2.4 节中:

使用外部或内部链接或存储类说明符 static 声明其标识符的对象具有静态存储持续时间。它的生命周期是程序的整个执行过程,它的存储值只在程序启动之前初始化一次。

于 2012-12-09T07:07:11.800 回答
1

The idea behind this requirement is to have all static storage duration object initialized at compile time. The compiler prepares all static data in pre-initialized form so that it requires no additional initializing code at run time. I.e. when the compiled program is loaded, all such variables begin their lives in already initialized state.

In the first standardized version of C language (C89/90) this requirement also applied to aggregate initializers, even when they were used with local variables.

void foo(void)
{
  int a = 5;
  struct S { int x, y; } s = { a, a }; /* ERROR: initializer not constant */
}

Apparently the reason for that restriction was that the aggregate initializers were supposed to be built in advance in the pre-initialized data segment, just like global variables.

于 2012-12-09T07:29:14.947 回答
0

用这个:-

int i=10,j=1;
int main()
{
  printf("%d",j);
}

虽然这是一个微小的变化,但它会起作用

于 2012-12-09T18:52:40.190 回答