I haven't used C very much in the last few years. When I read this question today I came across some C syntax which I wasn't familiar with.
Apparently in C99 the following syntax is valid:
void foo(int n) {
int values[n]; //Declare a variable length array
}
This seems like a pretty useful feature. Was there ever a discussion about adding it to the C++ standard, and if so, why it was omitted?
Some potential reasons:
- Hairy for compiler vendors to implement
- Incompatible with some other part of the standard
- Functionality can be emulated with other C++ constructs
The C++ standard states that array size must be a constant expression (8.3.4.1).
Yes, of course I realize that in the toy example one could use std::vector<int> values(m);
, but this allocates memory from the heap and not the stack. And if I want a multidimensional array like:
void foo(int x, int y, int z) {
int values[x][y][z]; // Declare a variable length array
}
the vector
version becomes pretty clumsy:
void foo(int x, int y, int z) {
vector< vector< vector<int> > > values( /* Really painful expression here. */);
}
The slices, rows and columns will also potentially be spread all over memory.
Looking at the discussion at comp.std.c++
it's clear that this question is pretty controversial with some very heavyweight names on both sides of the argument. It's certainly not obvious that a std::vector
is always a better solution.
There are situations where allocating heap memory is very expensive compared to the operations performed. An example is matrix math. If you work with smallish matrices say 5 to 10 elements and do a lot of arithmetics the malloc overhead will be really significant. At the same time making the size a compile time constant does seem very wasteful and inflexible.
I think that C++ is so unsafe in itself that the argument to "try to not add more unsafe features" is not very strong. On the other hand, as C++ is arguably the most runtime efficient programming language features which makes it more so are always useful: People who write performance critical programs will to a large extent use C++, and they need as much performance as possible. Moving stuff from heap to stack is one such possibility. Reducing the number of heap blocks is another. Allowing VLAs as object members would one way to achieve this. I'm working on such a suggestion. It is a bit complicated to implement, admittedly, but it seems quite doable.