Have a look at the code below,
This code compiles fine:
enum ids {
X,
Y,
NUM_IDS,
}
void some_func(void)
{
static char* const names[NUM_IDS] = { "name X" , "name Y"};
}
However this code doesn't compile: error: storage size of 'names' isn't constant
enum ids {
X,
Y,
NUM_IDS,
}
void some_func(void)
{
int nr_names = NUM_IDS;
static char* const names[nr_names] = { "name X" , "name Y"};
}
I think I misunderstood the meaning of a constant expression. Is it the case that in second way it is becoming a VLA which is not present in C90? Somebody please clarify.
static char* const names[nr_names]
is a VLA because nr_names
isn't a constant expression, but a (non-const) int
. Sure, in this short example it's always equal to NUM_IDS
, but you still can't do that.
On an unrelated side note, it is recommended that the char
is defined as const
, as modifying it won't work because it's part of the program's binary (in C++ it wouldn't let you have it non-const):
static const char* const names[NUM_IDS] = { "name X" , "name Y" };