How do compilers treat variable length arrays

In the C99 version of the C standard, variable length arrays are permitted. However, they are not permitted in any version of C++; you’re seeing a G++ extension. Note that Microsoft’s C compiler does not fully support C99; since G++ supports C99 it’s easy enough to apply the VLA support to C++ as an extension.

As to how the compiler usually implements VLAs, it’s the same as alloca() (except that it has to keep the size around for sizeof) – the compiler saves the original stack pointer, then adjusts it down by however many bytes it calculates that it needs. The downside is function entry and exit is a bit more complicated as the compiler needs to store where to reset the stack pointer to rather than just adjusting by fixed constants.

Leave a Comment