Definition of global variables using a non constant initializer

后端 未结 4 1390
夕颜
夕颜 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:14

    You could try using:

    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;
    }
    

    The only true C way is to initialize it at runtime. Although in C++ your code will work fine, without any compilation errors.

    The C standard clearly prohibits initialization of global objects with non-constant values. The Section 6.7.8 of the C99 standard says:

    All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

    The definition of an object with static storage duration is in section 6.2.4:

    An object whose identifier is declared with external or internal linkage, or with the storage-class specifier static has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

    0 讨论(0)
  • 2020-12-03 23:17

    Use this:-

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

    Though it is a minor change but it will work

    0 讨论(0)
  • 2020-12-03 23:19

    What is the reason behind this?

    C(unlike C++) does not allow initialization of global values with non constant values.

    C99 Standard: Section 6.7.8:

    All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题