2

AFAIK this code is not a valid c++ code by standard:

int a = 5;
int b[a];

but it seems many compilers can compile that code (mostly with warning) and it just behaves as expected. Am I wrong is is it compilers being nice to me?

Ali1S232
  • 3,373
  • 2
  • 27
  • 46
  • exact duplicate: [Dynamic array In Stack](http://stackoverflow.com/questions/1204521/dynamic-array-in-stack), [c++ initialize array with declared size as a value of an integer](http://stackoverflow.com/questions/6330695/c-initialize-array-with-declared-size-as-a-value-of-an-integer), ... – moooeeeep Nov 23 '11 at 08:24
  • @fmaas: didn't find those questions sorry – Ali1S232 Nov 23 '11 at 08:45
  • Actually I was aware of them just because I stumbled on this a few days ago by pure coincidence... – moooeeeep Nov 23 '11 at 09:03

3 Answers3

8

It is called variable length array (VLA) which is not allowed by Standard C++, any version of C++, though some GCC supports this as an extension.

If you're using GCC, then

  • Compile it with -pedantic option, you will see warning.
  • Compile it with -pedantic -Werror option, you will see warning turned into error.

VLA is allowed only by C99, though not by other versions of C.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Won't `-std=c++98` (or `-std=c++0x` if you're experimenting, rather than writing production code) suffice to suppress support of VLAs in g++? – James Kanze Nov 23 '11 at 08:38
  • @JamesKanze: No. It doesn't. I tried with `-std=c++98`, `-std=c++03`, and `-std=c++0x`, but none of them suppresses VLA in g++. It is weird, though. I'm using MinGw version 4.6.1 :-) – Nawaz Nov 23 '11 at 08:42
  • That sort of surprises me. But I'll admit that I've never tried it. (I always compile with `-std=c++98 -pedantic`. And in C++, I don't use `T[]` very often, either.) – James Kanze Nov 23 '11 at 09:10
4

The compiler is being nice. :)

It's actually part of the C standard, and some compilers (like GCC) extend C++ with this feature.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

This is the C99 standards Variable Length Array (or VLA), many compilers that can compile C99, often allow some of its features to be used in non-standard conforming C++ code.

G++ is one of these compilers, see here.

Community
  • 1
  • 1
Necrolis
  • 25,836
  • 3
  • 63
  • 101