M.X
M.X

Reputation: 195

Variable size array from table

I am new to c++ and I would appreciate if someone could help solving following problem.

When I want to create an array (Arr) with variable size (S), I do in the following way:

const int S=10;
int Arr[S];

However, in the code I am trying to write, I need to choose S from a Table. Let say I have following table:

int Table[3]={11, 21, 31};

and I choose S from the table and define Arr

const int S=Table[0];
int Arr[S];

I cannot compile this code because I get an error that S must have a constant have constant value.

I would appreciate any help/hint.

Upvotes: 0

Views: 733

Answers (1)

SergeyA
SergeyA

Reputation: 62603

To fix the problem, you need to declare Table constexpr:

void foo() {
  const int S=10;
  int Arr[S];
  constexpr int Table[3]={11, 21, 31};
  constexpr int S2=Table[0];
  int Arr2[S2];
}

Explanation: by declaring Table constexpr, you let compiler know that it knows it contents at compile time. Now it can be used whenver literal constants can be used, including array sizes. I'have shown the use of intermediate constexpr variable to illustrate this effect better, but you could use Table[0] as Arr2 size directly.

NB. constexpr is a keyword introduced in C++11, but I assume, it is safe to assume this dialect by default in 2016.

Upvotes: 1

Related Questions