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?

3

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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++?
@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 :-)
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.)
4

The compiler is being nice. :)

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

1 Comment

More specifically and accurately, it is part of C99 Standard.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.