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;
}
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:
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.
You're looking at GCC's variable length arrays. That's a GNU extension and is not standard C++.
This is a
gcc
extension and it seems likeclang supports this in limited cases
it is not standard C++ although it is validc99
. Ingcc
andclang
you can use the-pedantic
flag it will give you a warning like this ingcc
:and like this in
clang
:You could use
constexpr
(C++11) as a workaround in some situations: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