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];
10
  • 6
    It's an extension by your compiler, it's not standard C++. Commented Sep 20, 2017 at 14:47
  • Don't compile it with GCC. It will stop working Commented Sep 20, 2017 at 14:47
  • 1
    Add -pedantic-errors to your compiler flags. Also throw in -Wall -Wextra -Wfatal-errors for good measure. Commented Sep 20, 2017 at 14:49
  • @StoryTeller I use clang++ Commented Sep 20, 2017 at 14:50
  • @StoryTeller Wat? Stop working? Commented Sep 20, 2017 at 14:59

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. But now in my env it works, why the elements in the array is not 0?
@danche Because array is still uninitialized, it's not zero-initialized.
"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...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.