Jacob Thompson
Jacob Thompson

Reputation: 21

Can't use a variable for my array size but variable is declared as a const int

So I am having an issue with not being able to make a new array with a variable size (the variable is declared as const int)

Here is the code

#include <iostream>
#include <string>

int newArraySize;

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

   int const fin = newArraySize;

   int deduped[fin]; // Here is the error
}

The error I'm getting is

Error: Expression must have a constant value

I tried casting as a constant but still no luck (same error)

int const fin = const_cast<int const&>(newArraySize);
int deduped[fin]; 

Upvotes: 1

Views: 5644

Answers (2)

Mooing Duck
Mooing Duck

Reputation: 66912

C++ has (confusingly) two forms of const. Your fin is one type, but the other type is required for something to be the size of an array. The other type is newly called constexpr, and used to be "a compile-time constant". You see, all arrays have to be a fixed size known to the compiler in C++. So it's not enough to make a variable const, the compiler has to be able to figure out the value as well. So either newArraySize must be a compile time constant expression, or, more likely, you'll have to use a dynamic array, preferably managed by std::vector.

std::vector<int> deduped(newArraySize);

If you can't use a vector, there's other (worse) options: std::unique_ptr<int[]>, managing, dynamic memory yourself with int* deduped=new[newArraySize](); and delete deduped;, or making a local array with a compile-time-constant maximum size (1000), and separately keeping track of how many elements you're actually using.

Upvotes: 3

tom
tom

Reputation: 19153

newArraySize is not declared const. Do that and it'll work.

Upvotes: -1

Related Questions