0

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++

2
  • What is the error? What compiler are you using? int a[n]; is not standard and should not compile. Commented Mar 15, 2016 at 16:23
  • VLAs are not standard although GCC supports them siltently Commented Mar 15, 2016 at 16:24

1 Answer 1

1

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.

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

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.