Error “initializer element is not constant” when trying to initialize variable with const

前端 未结 5 1721
清酒与你
清酒与你 2020-11-21 13:02

I get an error on line 6 (initialize my_foo to foo_init) of the following program and I\'m not sure I understand why.

typedef struct foo_t {
    int a, b, c;         


        
5条回答
  •  独厮守ぢ
    2020-11-21 13:58

    It's a limitation of the language. In section 6.7.8/4:

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

    In section 6.6, the spec defines what must considered a constant expression. No where does it state that a const variable must be considered a constant expression. It is legal for a compiler to extend this (6.6/10 - An implementation may accept other forms of constant expressions) but that would limit portability.

    If you can change my_foo so it does not have static storage, you would be okay:

    int main()
    {
        foo_t my_foo = foo_init;
        return 0;
    }
    

提交回复
热议问题