Question

I'm seeing some code like this:

int foo()
{
  int sz = call_other_func();
  char array[sz];

  /* whatever */
}

I'm baffled at how this would work and even compile with gcc. The size of the array is supposed to be static and determined at compile time, no?

Was it helpful?

Solution 3

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

warning: ISO C90 forbids variable length array ‘array’ [-Wvla]

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

We can see from the C99 draft standard section 6.7.5.2 Array declarators paragraph 4 says (emphasis mine):

If the size is not present, the array type is an incomplete type. If the size is * instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations with function prototype scope;124) such arrays are nonetheless complete types. If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type.

Note that Visual Studio does not support VLA even though they now support C99

OTHER TIPS

This type of arrays are called variable length arrays (you would also like to raed: Arrays of Variable Length - GCC) and are allowed in C99 only. By using VLAs, the size of the array can be determine at runtime.

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

They're supported in C99 (and subsequently in C11).

Read more about how it works: The New C: Why Variable-length Arrays?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top