Definition of global variables using a non constant initializer

后端 未结 4 1406
夕颜
夕颜 2020-12-03 22:39
#include 

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

I get an error stating that initialization element is not a const

4条回答
  •  不思量自难忘°
    2020-12-03 23:21

    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.

提交回复
热议问题