0

Almost all sources on the internet say that an array needs to be declared with a value, that is known at compile time like constexpr variables. But this code works fine for me:

int main(){
  int a;
  std::cin >> a;
  int arr[a];
  //...
}

normally you'd exspect an compiler error, would't you? So I'm confused why this works (compiled with "g++ -m32 -g -std=c++20 main.cpp -o main" on linux)

  • 5
    Variable Length Arrays (VLAs) are *not* standard C++ ... but some compilers (notably g++) support them as an extension. I've closed this as a duplicate, though there may be a better target. – Adrian Mole Apr 10 '21 at 17:58
  • https://stackoverflow.com/questions/39334435/variable-length-array-vla-in-c-compilers – jtbandes Apr 10 '21 at 17:59
  • If you add the `g++` flags that disable the non-standard extensions, then it won't work and you'll be un-confused. – Eljay Apr 10 '21 at 19:17
  • By seeing the big number of beginner's questions on SO that uses VLA feature (often without knowing it is invalid C++), I am very frustrated that GCC and Clang do support VLA by default, and it is hard to make them reject the feature (`-pedantic-errors`). – prapin Apr 10 '21 at 19:38

0 Answers0