1

It is my understanding that the c++ compiler will not allow you to initialize an array with a variable yet this program compiles and runs on my computer, why is that?

// this should not compile because there is a variable in the array declaration

#include <iostream>

int main(){
    int x = 5;
    int ar[x];
    printf("hello world\n");
}
Mathew
  • 1,116
  • 5
  • 27
  • 59

2 Answers2

3

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ you can do this.

Check this answer / answer further.

Community
  • 1
  • 1
user2736738
  • 30,591
  • 5
  • 42
  • 56
-2

The size of the array may not be a variable.

Tornado
  • 1
  • 3
  • 4
    OP doesn't want to know whether it's allowed by the standard--they *already* know it's not allowed. They want to know why the compiler is letting them. – jaggedSpire Dec 28 '16 at 20:51