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++
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 (ie n
not being const
or constexpr
) although most compilers support it following C rules.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.