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

前端 未结 5 1724
清酒与你
清酒与你 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:44

    This is a bit old, but I ran into a similar issue. You can do this if you use a pointer:

    #include 
    typedef struct foo_t  {
        int a; int b; int c;
    } foo_t;
    static const foo_t s_FooInit = { .a=1, .b=2, .c=3 };
    // or a pointer
    static const foo_t *const s_pFooInit = (&(const foo_t){ .a=2, .b=4, .c=6 });
    int main (int argc, char **argv) {
        const foo_t *const f1 = &s_FooInit;
        const foo_t *const f2 = s_pFooInit;
        printf("Foo1 = %d, %d, %d\n", f1->a, f1->b, f1->c);
        printf("Foo2 = %d, %d, %d\n", f2->a, f2->b, f2->c);
        return 0;
    }
    

提交回复
热议问题