0

Using OnlineGBD, online g++ compiler I could use the: int arr[size]; syntaxis creating an array, but it doesn't work on the Visual Studio compiler. It says the variable should be a constant. Can someone please give me the syntaxis for the VS method? And explain the reason for this big difference between compilers.

Tried making the size variable a constant, but nothing worked.

qdqdqd
  • 11
  • 6
    `std::vector arr(size);` – πάντα ῥεῖ Jul 01 '23 at 07:50
  • 2
    You would do well to read up on [C++ containers](https://en.cppreference.com/w/cpp/container). Of which [std::vector](https://en.cppreference.com/w/cpp/container) is the one you need in this case. Note [cppreference.com](https://en.cppreference.com/w/) is the best reference site available for C++. Also have a look at the [C++ core guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines) you might find some real insights there too – Pepijn Kramer Jul 01 '23 at 07:52
  • 1
    `int arr[size];` -- This is not valid C++. Visual Studio is correct, and you were just fooled by something g++ has to offer as an *extension*. – PaulMcKenzie Jul 01 '23 at 09:37
  • Visual Studio is correct, variable length arrays have never been legal C++. The fact that you are/were unaware of this should make you reflect on how you are learning C++. How many other misconceptions do you have? Good sources for C++ learning [here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282) – john Jul 01 '23 at 09:40
  • Variable length arrays are legal in C, so that probably explains why they are sometimes made available as a extension to C++ users as well. You should use g++ with extensions disabled (or at least with warnings for extension use enabled). – john Jul 01 '23 at 09:47
  • @john I started studying C++ from school program, and g++ is what we use in class. I was very aware of this so I asked for the proper method and the reasoning behind this difference. I don't remember asking a stranger on the Internet telling me how to study so your answer carried zero useful information for me. Thank you anyways ;) And thanks everyone for explanation! – qdqdqd Jul 01 '23 at 10:43
  • @qdqdqd That information doesn't make your school seem very good if they didn't teach you what is a very basic fact about C++ arrays. I'm not trying to criticise you, just saying that to learn C++ you really do need an authoritative source of information about what is correct and what is not. g++ will not tell you, and apparently neither did your school. – john Jul 01 '23 at 10:48

0 Answers0