2

C++ tutorials like this say that the size of all arrays must be decided upon in advance of the program being run. For example, this is not allowed:

cout << "How many variables do you want? ";
int nVars;
cin >> nVars;

int anArray[nVars]; // wrong!  The size of the array must be a constant

But this trivial program does compile and execute fine. Should it?

Kian
  • 3,189
  • 3
  • 18
  • 16
  • It compiles, but (at least on gcc 4.8) it triggers [a warning](http://coliru.stacked-crooked.com/a/2975fa20de45fe34). – JBL Sep 20 '13 at 14:19

4 Answers4

6

This is a common extension implemented by C++ compilers, such as GNU's g++. Compile with -std=c++0x flag to treat such declaration as an error.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks. So is it stored on the stack, or the heap? – Kian Sep 20 '13 at 14:24
  • 1
    @user2432701 The array is on the stack. The compiler plays some tricks to know the size. – Sergey Kalinichenko Sep 20 '13 at 14:29
  • 1
    @user2432701 They are usually implemented on the stack, that is one of the core reasons many [feel VLAs are evil](http://www.clarkcox.com/blog/2009/04/07/c99s-vlas-are-evil/) which is similar to the argument [against alloca](http://stackoverflow.com/questions/1018853/why-is-alloca-not-considered-good-practice). – Shafik Yaghmour Sep 20 '13 at 14:42
  • 1
    Thanks for your help. If I run -pedantic from the command line, then it reports an error. But in CodeBlocks if I check -pedantic it doesn't. Do you happen to know why? Edit: I've found the solution in case any other reader has the same problem. In code blocks you cannot just hit "build" -- but you actually need to hit "rebuild". – Kian Sep 20 '13 at 15:26
4

Several compilers including gcc and clang support variable length arrays as an extension even though this is really a C99 feature.

If you use the -pedantic argument when building with gcc or clang both will give a warning similar to the following:

warning: variable length arrays are a C99 feature [-Wvla-extension]
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
2

It shouldn't in standard C++ but gcc/g++ and (I believe) MSVC both support extensions for such variable length arrays. There are options you can configure to disable the extensions though, in which case the code wouldn't compile.

In g++ it will fail to compile if you use -pedantic.

Mark B
  • 95,107
  • 10
  • 109
  • 188
1

Modern C/C++ compilers allows to use variable for define array size. Result as same as using alloca(). This is not standard right now, but gcc does this, about another - need to check.

olegarch
  • 3,670
  • 1
  • 20
  • 19