Initializing an array

103 views Asked by At

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.

2

There are 2 answers

0
richard.g On

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?

0
Kiril Kirov On

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.