Array size determined at runtime

I see the following code:

int foo() { int sz = call_other_func(); char array[sz]; /* whatever */ } 

I'm confusing how this will work and even compile with gcc . It is assumed that the size of the array is static and determined at compile time, no?

+6
source share
3 answers

This is a valid C99 function called variable length arrays (VLA), if you compile with gcc -std=c90 -pedantic , you will get the following warning:

warning: ISO C90 prohibits an array of variable length arrays [-Wvla]

using -std=c99 -pedantic will not give a warning, although both gcc and clang support VLA outside of C99 mode, as well as in C ++, which does not allow VLA as an extension .

Of Visual Studio does not support VLA , even if they now support C99

+2
source

This type of array is called variable length arrays (you would also like a raid: "Variable length arrays" - GCC ) and are only allowed on C99. Using VLA, the size of the array can be determined at runtime.

+4
source

"In programming, a variable-length array (or VLA) is an array data structure with automatic storage duration, the length of which is determined at run time (and not at compile time)." ( Wikipedia )

They are supported in C99 (and then in C11).

More on how this works: New C array: Why variable length?

+4
source

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


All Articles