-1

I thought that built-in arrays in C++ are statically allocated. But the following code works:

//...
int x;
std::cin >> x;
const int cx = x;
int array[cx];
//...

Why does it?

eesiraed
  • 4,626
  • 4
  • 16
  • 34
Glech
  • 731
  • 3
  • 14
  • 8
    That code works on *some* compilers that offer default-on extensions for variable length array. It doesn't work on other compilers and is not portable c++. You're being tricked by your compiler into thinking your code is valid c++. Another example of why you can't learn c++ by trial and error. – François Andrieux Nov 20 '18 at 19:18
  • One reason Variable Length Arrays are bad: `x` can support numbers that are very big. Bigger than the amount of Automatic storage available to that array. Now multiply that large number by the size of an `int`. Using an array of that size will commonly manifest as a stack overflow and much debugging can ensue as a result. – user4581301 Nov 20 '18 at 19:58

1 Answers1

3

Variable length arrays are not part of the C++ standard, however your compiler allows it. If you use the -pedantic-errors option with your compiler (assuming g++), this will throw an error as that option strictly enforces the standard.

jdrd
  • 159
  • 7
  • 1
    `-pedantic` causes the compiler to emit warnings, not errors. You need to add on `-Werror` or `-pedantic-errors` to get an compilation-halting error. That said, `-Werror` is something I recommend to anyone learning C++. Warnings are the first line of defense against logic errors and you should not ignore them. – user4581301 Nov 20 '18 at 19:47