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

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

    gcc 7.4.0 can not compile codes as below:

    #include 
    const char * const str1 = "str1";
    const char * str2 = str1;
    int main() {
        printf("%s - %s\n", str1, str2);
        return 0;
    }
    

    constchar.c:3:21: error: initializer element is not constant const char * str2 = str1;

    In fact, a "const char *" string is not a compile-time constant, so it can't be an initializer. But a "const char * const" string is a compile-time constant, it should be able to be an initializer. I think this is a small drawback of CLang.

    A function name is of course a compile-time constant.So this code works:

    void func(void)
    {
        printf("func\n");
    }
    typedef void (*func_type)(void);
    func_type f = func;
    int main() {
        f();
        return 0;
    }
    

提交回复
热议问题