-3

Why is it a bad idea to use variable length arrays in C++?

So, for example, this code:

int i = 0;
std::cin >> i;

int array[i]; // bad?

Edit: This is not a duplicate, as the duplicate asks for the reasons why the standard chooses to not put them in. This question asks what standard rules are being violated by variable length arrays.

  • Note: This is intended as a resource question for the countless question-askers who inadvertently put things like the above example in their code. Thus, I have answered this myself the best I can. Please feel free to add a better answer than mine. –  Jul 28 '19 at 05:48
  • 1
    Possible duplicate of [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – 273K Jul 28 '19 at 06:06
  • Re: "This question explains what standard rules are being violated by variable length arrays": Questions don't "explain" things, they "ask" things; and this question does *not* ask what standard rules are violated by VLAs. Rather, it merely asks why we shouldn't use them, and *one* answer (yours) answers the question by listing the relevant parts of the standard. (That said, I agree that this question is not exactly a dupe of that one; that question is more specific than this one.) – ruakh Jul 28 '19 at 06:14
  • C++, and as of C11, variable length arrays are an implementation defined feature: [C11 Standard - 6.10.8.3 Conditional feature macros](http://port70.net/~nsz/c/c11/n1570.html#6.10.8.3) "`__STDC_NO_VLA__` *The integer constant 1, intended to indicate that the implementation does not support variable length arrays or variably modified types.*" – David C. Rankin Jul 28 '19 at 06:15
  • @DavidC.Rankin VLAs are *never* in C++. – L. F. Jul 29 '19 at 01:29
  • @L.F. - that was my intent (it should formally read *"Notwithstanding that VLA's have never been part of the standard in C++, ..."*) – David C. Rankin Jul 29 '19 at 01:32
  • @DavidC.Rankin Well, I think the first three characters of your comment are intended to be "C" instead of "C++" ... – L. F. Jul 29 '19 at 01:33
  • The point being under the C++ standard and the current C standard any VLA you use is a compiler implementation and not part of the C++ standard and no longer a part of the C standard. (but I get what you are saying) – David C. Rankin Jul 29 '19 at 01:35

1 Answers1

7

Variable length arrays are supported by some compilers as an extension. They are not standard C++. Using VLAs makes your code non-portable.

A better alternative is to use std::vector.

int i = 0;
std::cin >> i;

std::vector<int> array(i);
R Sahu
  • 204,454
  • 14
  • 159
  • 270