Why is it so important for dimensions of the array
to be initialized from constexpr
? Would a regular variable
in a code bellow imply(if allowed legal) possible resizing
of the array
in the future?
int a=5;
int arr[a];
a=10;
Why is it so important for dimensions of the array
to be initialized from constexpr
? Would a regular variable
in a code bellow imply(if allowed legal) possible resizing
of the array
in the future?
int a=5;
int arr[a];
a=10;
Such a feature was proposed in n3497 but scrapped before C++14. C and C++ are completely different languages. Their syntax may be similar, but their evolution has diverged quite a bit. C++ aims to be more type safe and excise features that are dangerous or useless (like auto_ptr
).
A C++ "VLA" wouldn't be very useful anyways, to name a few features explicitly excluded from the proposal:
- multidimensional arrays, where other than the top level has a runtime bound (in analogy, array-new doesn't support that either)
- modifications to the function declarator syntax
- sizeof(a) being a runtime-evaluated expression returning the size of a
- "typedef int a[n];" evaluating "n" and passing that through the typedef
And undoubtably many more situations. C++ has a specification that's twice as large as C99 and then some, imagine the flood of bug reports for "why does this Quirk work" or "why doesn't this Quirk work" or "is this Quirk legal?" because of people trying to shoehorn VLAs everywhere.
And the paper even calls out a common criticism of VLA's:
Stack overflow becomes more likely, in particular if the size depends on external input and is not properly checked. Some environments might therefore prohibit the use of the feature. Such a prohibition can be easily enforced with a static analysis tool.
Imagine the amount of careless crap code that will be written if this was a feature. You may argue that in C++, you can shoot yourself in the foot. But C++ tries to at least adjust your sights so that the point of impact is the floor and not your foot.
What should you do instead?
Use std::vector
. Got complaints about performance for a simple program? You're prematurely optimizing.