Why aren't variable-length arrays part of the C++ standard? -


i haven't used c in last few years. when read this question today came across c syntax wasn't familiar with.

apparently in c99 following syntax valid:

void foo(int n) {     int values[n]; //declare variable length array } 

this seems pretty useful feature. there ever discussion adding c++ standard, , if so, why omitted?

some potential reasons:

  • hairy compiler vendors implement
  • incompatible other part of standard
  • functionality can emulated other c++ constructs

the c++ standard states array size must constant expression (8.3.4.1).

yes, of course realize in toy example 1 use std::vector<int> values(m);, allocates memory heap , not stack. , if want multidimensional array like:

void foo(int x, int y, int z) {     int values[x][y][z]; // declare variable length array } 

the vector version becomes pretty clumsy:

void foo(int x, int y, int z) {     vector< vector< vector<int> > > values( /* painful expression here. */); } 

the slices, rows , columns potentially spread on memory.

looking @ discussion @ comp.std.c++ it's clear question pretty controversial heavyweight names on both sides of argument. it's not obvious std::vector better solution.

there discussion kicked off in usenet: why no vlas in c++0x.

i agree people seem agree having create potential large array on stack, has little space available, isn't good. argument is, if know size beforehand, can use static array. , if don't know size beforehand, write unsafe code.

c99 vlas provide small benefit of being able create small arrays without wasting space or calling constructors unused elements, introduce rather large changes type system (you need able specify types depending on runtime values - not yet exist in current c++, except new operator type-specifiers, treated specially, runtime-ness doesn't escape scope of new operator).

you can use std::vector, not quite same, uses dynamic memory, , making use one's own stack-allocator isn't easy (alignment issue, too). doesn't solve same problem, because vector resizable container, whereas vlas fixed-size. c++ dynamic array proposal intended introduce library based solution, alternative language based vla. however, it's not going part of c++0x, far know.


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -