Take the 2-minute tour ×

There is such code:

#include <iostream>

int main()
  int size;
  std::cin >> size;

  size = size + 1;
  int tab3[size];

  tab3[0] = 5;
  std::cout << tab3[0] << " " << sizeof(tab3) << std::endl;
  return 0;

The result is:

$ g++ prog.cpp -o prog -Wall -W 
$ ./prog
5 24

Why does this code even compile? Shouldn't be length of array a constant variable?

I used g++ version 4.4.5.

share|improve this question
add comment

3 Answers

up vote 12 down vote accepted

Variable-length arrays in C++ are available as an extension in GCC. Compiling with all warnings should have alerted you to that fact (include -pedantic).

share|improve this answer
+1, tho I had no idea sizeof() can also be non-constant. If I ever thought of using sizeof() on that I'd expect it to fail for some reason. –  Michael Krelin - hacker Nov 14 '11 at 17:55
@MichaelKrelin-hacker: again, as an extension... VLAs require a runtime sizeof(), so it's part of the C99 standard. It's just not a very C++-type of thing. Think about decltype and all this... –  Kerrek SB Nov 14 '11 at 17:57
It is interesting though that there doesn't appear to exist any standardized method of allocating memory on the stack. We could handle object construction with placement-new, but it's just impossible in C++ to get a variable amount of raw memory on the stack. –  Kerrek SB Nov 14 '11 at 17:58
Sure, I don't doubt it's a standard, it's just that I had no idea and never thought of it. Probably alloca() is not standardized, but it's pretty common, not? –  Michael Krelin - hacker Nov 14 '11 at 18:03
There was a proposal to consider VLA's in C++ as well but the Standards committee dropped it because they considered the modifications to the type system for its support far outweighed the flexibility they would provide. –  Alok Save Nov 14 '11 at 18:04
show 9 more comments

It is a C99 feature, not a part of C++. They are commonly refered to as VLAs(Variable Length Arrays.

If you run g++ with -pedantic it will be rejected.

See GCC docs for more info.

See also: VLAs are evil.

share|improve this answer
add comment

GCC provide's VLA's or variable length arrays. A better practice is to create a pointer and use the new keyword to allocate space. VLA's are not available in MSVC, so the second option is better for cross platform code

share|improve this answer
add comment

Your Answer


