Definition of global variables using a non constant initializer

后端 未结 4 1403
夕颜
夕颜 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.

提交回复
热议问题