I read from a book saying that the following c++ code should not compile:
void f(int n, int m){
int a[n] , b[n][m];
}
because the size of the arrays are not determined at compile time.
But I tried it out and found no matter the function is a global one or a member function, I could get compilation successful using g++.
Was this something made legal in recent c++ implementation, or the book is simply wrong.
Thank you.
Edit
I saw a few replies immediately. I just have this wonder too in Java. I notice in java, this is supported (please correct me if this is also version dependent). So why the difference? Does it have anything to do with using references vs. objects? But still, in java, I can declare an array with variable length from function argument for primitives.
Edit 2
The following Java code did compile though, if you say it should not:
class Test1 {
public int[] f(int n,int k){
int[] c=new int[n];
Arrays.fill(c, k);
return c;
}
}
These are called Variable Length Arrays. They are not allowed in C++. But some compilers (such as GCC) support them as an extension.
In C99, Variable Length Arrays are allowed.
EDIT :
For your new question. The top answer for this question explains why C++ does not have variable length arrays.
Why no variable size array in stack?
EDIT 2:
In Java, arrays are objects which are stored on the heap rather than the call stack. Therefore the question is moot – all arrays are on the heap, hence VLAs don’t exist.