Possible Duplicate:
C/C++: Array size at run time w/o dynamic allocation is allowed?
In the following listing, clearly size of buf is determined by run-time constant j.
How does compiler generate code to allocate storage on stack(not knowing value of j at compile time)?
#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
srandom(time(NULL));
int i = random();
cout<< "random number: "<<i<<endl;
if(i%2==0)
i=2;
else
i=1;
const int j=i;
char buf[j];
std::cout<<"size of buf array: "<<sizeof(buf)<<endl;
return 0;
}
I’m assuming that you are using gcc, and hence the VLA extension. This is not standard C++ and it was dropped from C++0x (1x).
The reasoning is that it is not really all that useful and that a C++ implementation would be much more complex than one in C due to the stronger type system.
Really, if you are stack allocating arrays of unknown size, you are at the same time writing dangerous code that may very well blow the stack. If you know the size then it is a non-issue, otherwise just dynamically allocate it. There are of course perfectly valid use cases and it is a “nice to have” feature, but they ultimately decided against it.
Here is a good run down on the subject.