const int i = 100;
int *j = &i;
int array[i] = {0};
Is this legal? I read somewhere that without the &i, i and 100 would be added to the symbol-table, but because of the &i, storage is forced for i, and 100 would be stored in i at compile time; therefore the compiler would not be able to read the value of i (from storage) to allocate the array – is this true?
Here’s the language from the C99 standard:
So, sort of true, but not really relevant in this case. The compiler doesn’t have to create storage for
ito use its value elsewhere; it may simply use an immediate operand with the value of100in place ofi. Either way, the lineint j = &i;is unnecessary.iis not an integer constant expression, meaning it’s not a compile-time constant (in C; C++ is different in this regard); it’s a run-time variable whose value may not be modified during its lifetime.As of C99, you can specify array sizes using a run-time variable, even one declared
const, sowill allocate
arrayas a 100-element array ofint. However, you cannot use an initializer with a VLA, soint array[i] = {0};is not valid.Again, C++ is different, and doesn’t support VLAs at all. But since
iis declaredconst, C++ treats it as a compile-time constant, meaning your code should be legal C++ (it builds for me, anyway).More from C99: