1

I have following code:

const char *login_msg_type = "A";
struct handler handlers[] = {
    {"0", res_heartbeat},
    {login_msg_type, res_login},
};

Compiler throws an error stating that "initializer element is not constant". Well, I know I can #define that value but I want the variable to have a type. Is it possible?

Evgeniy
  • 756
  • 8
  • 17
  • 1
    Did you try `const char * const`? – Yunnosch May 29 '22 at 19:11
  • I did not knew that is possible to state `const` twice. Amazing, thank you. It is required to stick to this order `const char * const`? I tried `const const char *` and it did not worked. – Evgeniy May 29 '22 at 19:20
  • 2
    `const char *` is a variable pointer to a const char, `char * const` is a const pointer to a variable char, `const char * const` is a const pointer to a const char. – Arkku May 29 '22 at 19:29
  • 1
    Related https://stackoverflow.com/questions/54135942/why-initializer-element-is-not-a-constant-is-not-working-anymore , the second example is very similar. The question is "*Can* const variable be available at compile time?". They "can", but it's not part of the language, not all compilers (versions) support it, and it's a compiler extension. – KamilCuk May 29 '22 at 19:59

1 Answers1

1

As @Yunnosch, @arkku stated in the comments section, the answer is

const char * const login_msg_type = "A";

const char * is a variable pointer to a const char, char * const is a const pointer to a variable char, const char * const is a const pointer to a const char.

Evgeniy
  • 756
  • 8
  • 17
  • What does your answer adds to the discussion? The answer should contain an explanation. You just point on the other person's comment, that, explained it better. – user14063792468 May 29 '22 at 20:35
  • It adds an answer. Many people do not read comments, so I decided to write one. And I think the answer should resolve the problem or answer the question, first of all. – Evgeniy May 30 '22 at 13:43