This question already has an answer here:
-
C++: Why does int array[size] work?
3 answers
I was surprised to find out that it is possible to allocate an varying-length array on the stack in C++ (such as int array[i];
). It seems to work fine on both clang and gcc (on OS/X) but MSVC 2012 don't allow it.
What is this language feature called? And is it an official C++ language feature? If yes, which version of C++?
Full example:
#include <iostream>
using namespace std;
int sum(int *array, int length){
int s = 0;
for (int i=0;i<length;i++){
s+= array[i];
}
return s;
}
int func(int i){
int array[i]; // <-- This is the feature that I'm talking about
for (int j=0;j<i;j++){
array[j] = j;
}
return sum(array, i);
}
int main(int argc, const char * argv[])
{
cout << "Func 1 "<<func(1)<<endl;
cout << "Func 2 "<<func(2)<<endl;
cout << "Func 3 "<<func(3)<<endl;
return 0;
}
You're looking at GCC's variable length arrays. That's a GNU extension and is not standard C++.
This feature is called Variable Length Arrays or VLAs.
It's part of C99 standard (and also C11) but is not supported by C++11. However, as you see some compilers accept it as an extension.
Finally, a similar feature (but not exactly the same as C99's VLAs) was approved at the C++ committee meeting in Bristol (April 2013) and is in the current draft of C++14.
Two main differences between C99's VLAs and C++14's are illustrated below:
void f(std::size_t n) {
int a[n];
unsigned int x = sizeof(a);
// ...
int matrix m[n][n];
}
In C99, the expression sizeof(a)
is evaluated at runtime. In C++14 this is illegal. In addition, multidimensional VLAs are not supported by C++14.
For more information on C99's VLAs see this DrDobb's article.
For more information on C++14's runtime-sized arrays see N3639, the paper that was approved in Bristol.
Update: In the Chigago meeting, the committee decided to remove this feature from C++14 and instead put it in a separate document, a Technical Specification (TS) on array Extendions (TS). In addition, the TS also includes the template class dynarray
which is somewhat related to arrays of runtime bounds.
The main reason it was dropped from C++14 is that the committee wants to get feedback from implementation and user experience before standardizing these features.
This is a gcc
extension and it seems like clang supports this in limited cases
it is not standard C++ although it is valid c99
. In gcc
and clang
you can use the -pedantic
flag it will give you a warning like this in gcc
:
warning: ISO C++ forbids variable length array ‘array’ [-Wvla]
and like this in clang
:
warning: variable length arrays are a C99 feature [-Wvla-extension]
You could use constexpr
(C++11) as a workaround in some situations:
constexpr int getArraySize (int factor) {
return 2 * factor + 1;
}
int my_array[getArraySize(3)];
Actually in C++14, this limitation shouldn't be there any more: http://isocpp.org/blog/2013/04/n3639-runtime-sized-arrays-with-automatic-storage-duration