Is this C++ code correct?
const size_t tabsize = 50;
int tab[tabsize];
The problem is that I\'ve already seen numerous conflicting opinions
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 #define
d (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.