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 に答える
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 に答える