1

As C++ primer said, we can't use variable as the dimension of builtin array, so the following code did not work

int length = 3;
int array[length] = {0, 1, 2};

the error is

error: variable-sized object may not be initialized

But why following code works?

int length = 3;
int array[length];
Barmar
  • 741,623
  • 53
  • 500
  • 612
danche
  • 1,775
  • 15
  • 22

1 Answers1

3

This is an extension by your compiler called a Variable Length Array (VLA) and is not in the C++ standard which means that this code can break at any moment you switch compilers or the compiler vendor decides to no longer support this feature. If you want a variable length array that does not depend on this extension but instead on the standard you should use a std::vector.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
  • Thanks. But now in my env it works, why the elements in the array is not 0? – danche Sep 20 '17 at 14:53
  • @danche Because `array` is still uninitialized, it's not zero-initialized. – Hatted Rooster Sep 20 '17 at 14:54
  • "or the compiler vendor decides to no longer support this feature", well, for extensions which are rather well established and documented, and have existed for longer than C++ has been standardized, I think that's just FUD. Features can't be retroactively removed from current versions. I'd be more worried about using latest C++ standard features and encountering a compiler bug, which will silently alter code behavior when it gets fixed in a minor version bump, or when compiling with different compiler... – hyde Sep 20 '17 at 15:46