Arrays of variable length in C and their initialization in place

C99 allows you to define arrays with a variable size, that is, the size used to determine the array can change at runtime. A code snippet to explain this will 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 this is a difference in behavior for an array, which is a variable length and a constant of length. In both cases, the array will be assigned memory when the function is called.

+4
source share
3 answers

This is because the compiler does not know how many zeros to "fill" the remaining elements.

Statement

 char arrA[3] = { 0 }; 

can easily be translated into

 char arrA[3] = { 0, 0, 0 }; 

at compile time, while a variable-length declaration cannot.

Since C does not have a runtime system, the compiler will have to add code for dynamic input with zeros depending on the given length. Standard C aims to be minimal with maximum power for the programmer, and therefore such things are avoided. Starting with C11, variable-length arrays have been removed from the standard and marked as an optional function.

+4
source

It seems that this standard is not allowed by the standard, if we look at the standard section of the C99 project 6.7.8 Paragraph 3 of the initialization says (emphasis added):

The type of the object to be initialized must be an array of unknown size or an object type that is not an array of variable length .

Due to the fact that, most likely, because support for initializing an array of variable length will require an indefinite amount of work at runtime.

+4
source

Hypothesis: C is a mid-level language, and the standardization committee did not want to include operations in the base language (counting the library as a separate language) that perform a volume of work that was not determined at compile time.

All the basic C operations that come to my mind at the moment (maybe someone will correct me) require only a certain amount of work defined at compile time: calling a function, multiplying two numbers, assigning a structure to another, and soon. All of them can be executed with the execution of several machine instructions, which are fixed during compilation.

Even to allocate space for a variable-length array, only compilation time is required: calculate the size and subtract it from the stack pointer. In contrast, initializing all of this space requires some work at runtime. This is not consistent with the nature of C.

Library programs may require some workload defined at runtime, such as memset .

+2
source

Source: https://habr.com/ru/post/1502646/


All Articles