2

I am doing the following for initializing an array in c++

int a;
cin>>a;
float b[a];

This works and compiles in my computer. IS this correct? I thought that we can only do this if a was a const int.

3
  • It's a compiler extension, although it's coming in a TS soon. Use -pedantic(-errors). Commented Dec 20, 2013 at 14:09
  • @chris could you please elaborate as I am new to this and did not understand your reply. Can i continue coding using this kind of a inititlization? Commented Dec 20, 2013 at 14:11
  • 2
    The answer elaborates on most of it. Assuming you're using GCC or Clang, you can compile with -pedantic to get a warning, and VLAs are coming to C++ in a technical specification in 2014. Commented Dec 20, 2013 at 14:15

2 Answers 2

1

Depends on you definition of "correct".

This is called variable-length array (or just VLA) and it's not officially supported in the current versions of C++ (100% sure for C++03 and before, 99.99% sure for C++11), but it is in C.

Some compilers allow this as a compiler extension.

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

Comments

1

It's not about whether a is a constant int. It's about whether a has a initial value assigned at comipling time. Compiler needs to allocate storage according to a const int value. C++ standard doesn't support variable length array right now.

In C99, this syntax of variable length array is valid, but C++ standard says no. It is a very useful feature, leaving all the hairy memory allocating stuff to the compiler.

In GCC and Clang, this feature is supported as a compiler extension, so you won't get any warning and error. But MSVC compiler will put an error message that says cannot allocate an array of constant size 0, So it is compiler specific.

The compiler that supports this feature may have convert your code with new operator.

int a;
cin>>a;
float *b = new float[a];

This is valid in C++ standard.

Another thing is that though it is called variable-length array, it is not length-variable at all. Once it is defined, its length is a constant value which never change. You can't expand it or shrink it.

It is much better to use the vector container which is truly length variable, and with much more scalability and adaptivity.

See the post for more discussion on Why aren't variable-length arrays part of the C++ standard?

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.