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)

4
  • 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. Commented Apr 10, 2021 at 17:58
  • stackoverflow.com/questions/39334435/… Commented Apr 10, 2021 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. Commented Apr 10, 2021 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). Commented Apr 10, 2021 at 19:38

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.