user4385532
user4385532

Reputation:

Can an array be declared with a size that is a const variable not a constexpr?

Is this C++ code correct?

const size_t tabsize = 50;
int tab[tabsize];

The problem is that I've already seen numerous conflicting opinions on that matter. Even people at ##c++ IRC channel and programming forums claim radically different things.

Some people say the above code is correct.

Others argue that it is not, and that it should necessarily be like this:

constexpr size_t tabsize = 50;
int tab[tabsize];

Since I'm already confused enough by conflicting opinions of "C++ experts", could I please ask for a reasonably backed up answer? Many thanks!

Upvotes: 6

Views: 3434

Answers (1)

bolov
bolov

Reputation: 75668

In C++ constant integers are treated differently than other constant types. If they are initialized with a compile-time constant expression they can be used in a compile time expression. This was done (in the beginning of C++, when constexpr didn't exist) so that array size could be a const int instead of #defined (like you were forced in C):

(Assume no VLA extensions)

const int s = 10;
int a[s];          // OK in C++

const int s2 = read(); // assume `read` gets a value at run-time
int a2[s2];       // Not OK

int x = 10;
const int s3 = x;
int a3[s3];       // Not OK

So the answer is yes, you can use a const integer variable as the size of an array if it was initialized by a compile time constant expression


This is my answer from another question. That question is about int vs float const and constexpr, so not exactly a duplicate, but the answer applies here very nicely.

Upvotes: 17

Related Questions