2
int n;
cin >> n;
const int size = n;
int arr[size];

I'm getting a compiler error message "Expression must have a constant value". I'm using visual studio 2013. But the array size is a const int, whose value does not change. How am I getting a compiler error?

Neko
  • 21
  • 1
  • 2
    n is still runtime depending and C++ doesn't support dynamic arrays. So the compiler wants to have a compile-time-constant statement. – user6556709 May 01 '19 at 05:23
  • `int arr[size];` is called a [variable length array](https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html) (VLA). VLA is present in C99 but it is a GCC extension for C90 and C++. Also, `const int size = n;` is `const` but not a `constexpr`. Since you are C++, why not use a `std::vector`? – jww May 01 '19 at 06:04
  • `size` is constant, but it's not a **compile-time** constant. Array sizes are required to be compile-time constants. – Pete Becker May 01 '19 at 12:13

1 Answers1

0

There is no relation for compilation error and visual studio version. Compilation erros occur when you are violating C++ concepts. Here, you're receiving array size as an argument from the user and it is dynamic value. In C++ you cannot create dynamically varying size arrays, instead static arrays is possible. Else you need to switch your data structure either to list or map, based on your requirement.

YatShan
  • 425
  • 2
  • 8
  • 22