Sithideth Bouasavanh
Sithideth Bouasavanh

Reputation: 1051

compile-time array initialization with non-const variable size

I having a confusion about what is going on behind the scene of array initialization.

int n= 3;
int a[n]; // compile succeeds

but,

int n = 3;
int a[n] = {1, 2, 3};   // compile error

error message from codeblock:

error: variable-sized object 'a' may not be initialized

My understanding is: first snippet, n elements are allocated but uninitialized. Second one allocates n elements and initializes them to {1, 2, 3}. Both do almost the same thing, but why second one causes error.


Please clarify my understanding or leave me some resources (I've tried, but couldn't find the close answer).


compiler: mingw32-g++

Upvotes: 0

Views: 658

Answers (1)

ftynse
ftynse

Reputation: 797

In C99, it's explicitly forbidden by the standard (6.7.8p3)

The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type.

Even though we can see that n is a constant value, it is not marked as such.

AFAIK, C++ standard does not allow for variable-length arrays (i.e. n not being const or constexpr) although most compilers support it following C rules.

Upvotes: 1

Related Questions