Search code examples
arraysinitializationconstantsc89

Why is an array with const length considered to be a variable-sized object by the compiler?


In C, variable-size arrays cannot be initialized, i.e.,

int size = 3;
int array[size] = {1, 2, 3}; /* error: variable-sized object may not be initialized */

We can define size as a pre-processor macro to make it work:

#define size (3)
int array[size] = {1, 2, 3}; /* works */

I'd prefer to use constants instead of macro, so I'd like to do:

const int size = 3;
int array[size] = {1, 2, 3}; /* error: variable-sized object may not be initialized */

Question: Why does this last variant not work? if const is telling the compiler that I have no intentions of modifying the variable, why doesn't it deduce that the array isn't variable-sized?

I also tried to make size static, to no avail:

static const int size = 3;
int array[size] = {1, 2, 3}; /* error: variable-sized object may not be initialized */

Note: I know that I could just do

int array[] = {1, 2, 3};

However, size is later used to iterate over the array so I'd like the compiler to throw a warning ifsize does not match the actual size of the array.


Solution

  • I found out why neither a variable of type const int nor const static int can be used to declare an array: The array size needs to be a constant expression. In C, a constant expression is something like a literal constant or a sizeof expression (the latter only since C99), BUT NOT a const variable. Curiously, in C++ a const variable is a constant expression and can be used to declare an array.