2

I try to understand, what happens when creating an array of unknown size on stack at compile time. Let consider this code:

int main()
{
    int x;
    cin >> x;

    int tab[x];
}

I found a lot of information about this saying that you can not create an array of unknown size on the stack, but I didn't find any information why does the C++ compiler allows it, or maybe some of them do? What happens when creating such array? Is it even created on stack or already on heap?

Does the GCC compiler have some option to turn on, thanks to which such a constructions would be considered as errors or at least warnings?

Tom
  • 1,027
  • 2
  • 16
  • 35

1 Answers1

4

C++ does not permit Variable Length Arrays (VLAs).

However, the most recent C standard does, so it can sometimes be found as an extension, such as it is with the GCC.

When compiling, make sure so explicitly select a language (chose C++17 or later if you can) and ask for pedantic (strictly standards-conforming) behavior.

Dúthomhas
  • 8,200
  • 2
  • 17
  • 39
  • Thank you. Right now I can only use C++1z, but it still allows the VLAs, so I have to use this compiler option: (-Werror=vla) – Tom Apr 16 '18 at 17:29
  • 1
    It turns out that also the flag `-pedantic-errors` can be used instead of `-Werror=vla` – Tom Apr 16 '18 at 17:46