Variable Length Arrays

Last week, my buddy Kent sent some mail, lamenting the fact that this code didn’t work quite as well as the traditional countof macro:

template <typename T, unsigned N>
inline unsigned countof( T const (&)[N] ) { return N; }

int main()
        int a[10];
        int b[countof(a)]; // BOOM!

The heart of the matter lies in the fact that the standard does not allow this:

int array[foo()];

We simply can’t force compilers to stop and analyze foo — we can’t standardize the optimizer. Some might do better analysis and might prove more than others, leading to a portability nightmare. Furthermore, it’s not guaranteed that the foo’s definition will even be available at this point. We can’t require whole-program optimization (aka, LTCG).

It all made sense until Bheeshmar chimed in with the following shocker: “It works on GCC”. I was confused until I realized that GCC already supports C99-like variable length arrays.

Normal C arrays are terribly stupid. Their size must be known at compile time (yet they manage to completely forget this information after their point of definition). VLAs don’t have this restriction because they simply do an alloca-style stack allocation at runtime.

OK so VLA support enabled Kent’s code to build. But wait, Kent’s array has a compile-time constant size. What’s going on here?

With VLAs, we can define arrays without fear. The compiler thinks to himself, “No big deal, I can call alloca() later if I must.” Because of this safety net, compilation can proceed to the optimizer which may eventually prove that the array actually has a compile-time constant length. Eventually, a smart optimizer might turn the VLA back into a regular ‘ole static array, saving some stack manipulation.

Let me say that again in case you missed it: VLA support enables us to discover that we don’t need VLA support.


1 Response to “Variable Length Arrays”

  1. 1 mark++ » Blog Archive » VLA Redux Trackback on September 19, 2006 at 11:43 am
Comments are currently closed.

%d bloggers like this: