Search code examples
carraysgccvariable-length-array

Array size determined at runtime


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?


Solution

  • 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