This is wrong since a variable sized object may not be initialized
int size = 4;
int array[size] = {1};
size
is a variable, but doesn't the compiler know its value when it creates array
(Isn't size
assigned an initial value of 4 at compile-time?)? Let size
change after that, why would it be an issue? I mean, these are consecutive instructions, what could possibly alter the value of size
before the array is declared?
Second question: Why is this not allowed:
const int size = 4;
int array[size] = {1};
I am declaring size
as a const. I know that const != read-only, and that declaring size
as a macro is the correct way to go about it. But if I promise the compiler using const that I wont change the value of size
, why is it not allowed?
The answer to the first question is "because the language specification says so". Although a compiler may be able to infer the size of the array, doing so requires some static analysis which is not trivial when the array size is not a compile-time constant expression.
As to why initialization of VLAs is not allowed: one reason I can think of is that it is not known until runtime how many elements they will contain, so a VLA may be shorter than its initializer list, which would invoke undefined behavior. I can't tell for sure if this is (one of) the real reason(s), though.
Second question: Why is this not allowed:
It is allowed, unless you the writers of your compiler are living in a cave (for example, the engineers over at Microsoft do -- their C compiler is one rare example of a widely used compiler that still does not support C99, 15 years after its standardization.). Any modern, decent C compiler should enable you to use variable-length arrays which are present in C99. Compilers that already implement C11 may or may not opt to support VLAs (as it's an optional feature of the latest standard).