visual c++ - Array allocation in C++ on stack with varying length -
this question has answer here:
- c++: why int array[size] work? 3 answers
i surprised find out possible allocate varying-length array on stack in c++ (such int array[i];
). seems work fine on both clang , gcc (on os/x) msvc 2012 don't allow it.
what language feature called? , official c++ language feature? if yes, version of c++?
full example:
#include <iostream> using namespace std; int sum(int *array, int length){ int s = 0; (int i=0;i<length;i++){ s+= array[i]; } return s; } int func(int i){ int array[i]; // <-- feature i'm talking (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 @ gcc's variable length arrays. that's gnu extension , not standard c++.
Comments
Post a Comment