0

Why is this code compiling successfully, without any warning:

int m,n;
cin >> m >> n;
int arr[m][n];

[compiled with MinGW with Code::Blocks]

Shouldn't atleast one of m or n must be constant at compile-time ?? I've seen variable length arrays accepted but they were all one-dimensional. Why is this two dimensional also being accepted ??

Moreover this is also running totally fine:

int arr[m][n][p];
  • 3
    In code::Blocks Setting->Compiler...->Compiler Setting-> Mark Enable warning demanded by Strict ISO C and ISO C++ (-pedantic), then you should get two warning. – ashiquzzaman33 Feb 11 '16 at 04:41

3 Answers3

1

This is a non-standard GCC extension. Many other compilers like Visual C++ don't support VLA.

LIVE DEMO

ashiquzzaman33
  • 5,781
  • 5
  • 31
  • 42
0

Array dimensions only have to be defined on initialisation. Let's say that the user enters m = 4 and n = 2:

int arr[m][n];

...becomes...

int arr[4][2];

Voilà, the compiler has all the information it needs to initialise the array.

I think that this is what you are thinking of:

int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};    // this code will fail

The compiler will only automatically detect array size for the first dimension.

int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};   // this code will work
-1

Syntax of your code is correct by c++ consepts. But if you enter m or n less than zero or m*n more than about 10000, it will be exaption. That's why you write your code in try-catch like below:

int m,n;
cin >> m >> n;
try {
    int arr[m][n];
} catch (Exception e){
    cout << "Error";
}
Akbar
  • 430
  • 4
  • 18