C++ Variable-Length Arrays

2015-08-01 #c++ #vla

Another letter I wrote to my C++ classmates at UCSCx.

Hi, All,

In the previous magic square homework, I happily wrote the following line:

int map[n][n]; //n is a non-constant

Our teacher may be mad at you if your code looks like this(and your score may suffer), but it actually compiles, both on gcc and clang!

Turns out, this feature is called VLA(variable length array). It s specified in C99, but not in C++(who says C++ is a superset of C?). However, both gcc and clang implemented it anyway, as a “language extension”. If you don’t like this feature, you can enable warning by adding a -pedantic flag while you compile. Depending on your compiler, it would cry something like this:

warning: ISO C++ forbids variable length array 'arr'

There were some disputes though:

https://groups.google.com/forum/#!topic/comp.std.c++/K_4lgA1JYeg

(Note that the thread was created by Scott Mayers, the one behind Effective C++ and Effective Modern C++!)

Seems like the dispute has not settled yet. As someone from Java/C#, I really like this feature. Who knows, maybe it will be included in C++14. What do you think?

Happy hacking,

Kuan-Ying Chou