0

I've been trying to find answers for this lately, but I just can't seem to understand why the compilers for C++ that Microsoft has been using can't compile such a code :

    #include<iostream>

int main()
{
    int n;
    std::cin >> n;

    int x[n];
}

It gives those errors :

enter image description here

However, this code compiles on a lot of different compilers.

Could someone point me to somewhere, I couldn't find any answers for this.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • The error might be confusing but it is not valid C++. You cannot declare arrays whose size is not a compile time constant. The "lot of other compilers" are in non-compliance here. – Tanveer Badar Aug 15 '20 at 05:56
  • 3
    Using `int x[n];` with a non-constant `n` is not valid C++. These are called Variable-Length Arrays (VLA) and they're valid only in C. Use `std::vector` instead. – Aziz Aug 15 '20 at 05:56

3 Answers3

0

See How to make an array with a dynamic size? General usage of dynamic arrays (maybe pointers too)? for discussion on the matter. Briefly, C++ requires that raw arrays have a constexpr for their size, so they it knows how much memory to allocate for it at the moment it's declared instead of at runtime after receiving user input. Some compilers I suppose are more permissive on this.

Nathan Pierson
  • 5,461
  • 1
  • 12
  • 30
0

Variable length arrays are not standard C++. Some compilers provide them as a language extension but they are not portable.

jkb
  • 2,376
  • 1
  • 9
  • 12
-1

This code shouldn't compile.

In C++, arrays are statically allocated and their required memory must be specified at compile time.

Hence, a user input is not a suitable value for array declaration. If you want a dynamic array, you can try using malloc like this:

#include<iostream>

int main()
{
    int n;
    std::cin >> n;

    int* x = (int*)malloc(n*sizeof(int));
}

This way, the array is actually stored in heap, and can have any arbitrary size, changing over lifetime of the program.

Another alternative is std::vector of course.

Ali Tou
  • 2,009
  • 2
  • 18
  • 33
  • 2
    `malloc` is the last thing you should use to allocate dynamic memory.Before you pull `malloc` out of the toolbox, you should have already rejected [Standard Library containers](https://en.cppreference.com/w/cpp/container), [Smart pointers](https://en.cppreference.com/w/cpp/memory), and [`new`](https://en.cppreference.com/w/cpp/language/new) The answer should start with `std::vector`, not end with it. – user4581301 Aug 15 '20 at 06:19
  • You're right. I just wanted to clear the reason why static arrays are not compilable and what the solution is, in an OS-view way. – Ali Tou Aug 15 '20 at 06:51