Reputation: 2785
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.
Upvotes: 1
Views: 109
Reputation: 15793
The problem is that VLAs are not allowed to have static storage duration
Quoting from ISO 9899 6.7.5.2 Array declarators
If an identifier is declared to be an object with static storage duration, it shall not have a variable length array type.
So, you are not allowed to declare a static VLA in general. Because nr_names
is not constant, you are not allowed to use static in your second code.
The first code is correct, as NUM_IDS
is constant expression.
Other problem with your second code is that a VLA cannot be initialized.
I quote from ISO 9899 6.7.8 Initialization
The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type
Upvotes: 1
Reputation: 16876
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" };
Upvotes: 3