1

For some reason, in the past, I recall not being able to do something like:

int arraySize;
cin >> arraySize;

int array[arraySize];

But recently, I tried this again and its not causing any issues. I could've sworn before this was something that threw an error in my compiler (macOS Sierra, Xcode 8.1). Was anything in the language updated to allow this? - I could be entirely remembering incorrectly and this wasn't an issue before, but I'm not sure. I thought array sizes had to be defined during compilation and the user couldn't pick that (which is where you would implement a dynamic array).

JosephTLyons
  • 2,075
  • 16
  • 39
  • 1
    It's probably compiler extension - don't use it to make code portable – W.F. Nov 22 '16 at 21:24
  • @W.F. - I dont plan on using it, I'd rather use a vector or a dynamic array, I was just very confused on why this was possible now, all-of-the-sudden. – JosephTLyons Nov 22 '16 at 21:29
  • Whole `int[N]` is a type in c++ and as such it must be entirely known at compile-time including `N`. I don't think it will ever change... – W.F. Nov 22 '16 at 21:33

2 Answers2

17

The C++ Standard does not support variable length arrays though some compilers can have their own language extensions that allow to use VLAs in a C++ program.

Thus this code snippet

int arraySize;
cin >> arraySize;

int array[arraySize];

is not C++ compliant.

Use instead the standard C++ class std::vector.

As for C then according to the C Standard implementations may conditionally support VLAs.

You can check whether an implementation supports VLAs. From the C Standard (6.10.8.3 Conditional feature macros)

1 The following macro names are conditionally defined by the implementation:

__STDC_NO_VLA__

The integer constant 1, intended to indicate that the implementation does not support variable length arrays or variably modified types.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
8

Was anything in the language updated to allow this

No. Variable length arrays (aka. VLAs) are a compiler specific extension.

The c++ standard never allowed this (unlike the c99 standard does so contrarily).

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190