The following code, in global scope, doesn’t compile:
const char *one = "1";
const char *two = "2";
char *nums[2] = {one, two};
The error message is “initializer element not constant” – which surprises me, since the variables one and two are both declared as constant. Making nums const doesn’t fix the problem. Declaring nums with string literals (char *nums[2] = {"1", "2"};) does fix the problem, but for readability reasons, I’d rather not do it this way in my actual code.
Is there a decent way to get this working?
C does not allow global initialization from variables, even if those are themselves
const. By comparison to C++, C has a much stricter notion of a “constant expression”.At present,
oneis a mutable pointer, so it cannot possibly be considered a constant expression, but even the more correctconst char * const one = "1";wouldn’t do in C. (It’d be fine in C++.)You’ll have to say: