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;
}