0

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.

6
  • Remove "const" and make sure your compiler supports VLAs. Commented Feb 2, 2016 at 16:58
  • 1
    I don't think VLA are standard conform. Is it not only gcc (and maybe clang) which have it? Commented Feb 2, 2016 at 17:02
  • 8
    C++ does not have "arrays with variable size"; the size is part of the array type. You want std::vector. Commented Feb 2, 2016 at 17:02
  • 4
    variable sized arrays are called std::vector in C++ Commented Feb 2, 2016 at 17:03
  • Make Table const as well, or S isn't truely const, which explains the error. Commented Feb 2, 2016 at 17:03

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I wonder if the size the OP wants is actually statically known. I'd have guessed it was known only at run-time, but the question is not so clear in that aspect.
I am using visual studio 2012 and when I type constexpr, I get error. However, I have fixed the problem by defining vector instead of array. However, thank you very much for the answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.