Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable length arrays in C and initializing it in place [duplicate]

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.

like image 581
user2676432 Avatar asked Dec 26 '22 20:12

user2676432


2 Answers

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.

like image 133
Johan Henriksson Avatar answered Jan 10 '23 23:01

Johan Henriksson


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.

like image 39
Shafik Yaghmour Avatar answered Jan 11 '23 01:01

Shafik Yaghmour