C99 allows defining arrays with non-constant size, i.e. the size used to define an array can change on runtime. Code snippet to explain it would be,
void dummy_function1(unsigned int length) {
char arrA[length]; //Allowed
.
.
}
However, it does not allow initializing it in place, i.e.
void dummy_function2(unsigned int length) {
char arrA[length]={0}; //Not Allowed, compiler throws an error
char arrB[10]={0}; //Allowed
.
}
I do not understand, why is this difference in behavior for array which is variable length and the one which is constant length. In both cases, the array would be given memory when the function is invoked.
This is because the compiler does not know how many zeroes to "fill out" the remaining elements with.
The statement
char arrA[3] = { 0 };
can easily be translated to
char arrA[3] = { 0, 0, 0 };
during compile time, while the variable length declaration can not.
Since C does not have a runtime system, the compiler would have to add code to dynamically pad with zeroes depending on the given length. The C standard strives to be minimal with maximum power to the programmer, and therefore things like this are avoided. As of C11, variable-length arrays have been removed from the standard and are labeled as an optional feature.
It looks like this is not allowed by the standard if we look at the C99 draft standard section 6.7.8
Initialization paragraph 3 says(emphasis mine):
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.
As to why most likely because supporting initialization of a variable length array would require indeterminate amount of work at run-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With