Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const (but not constexpr) used as the built-in array size

Tags:

c++

I understand that the size of the built-in array must be a constant expression:

// Code 1
constexpr int n = 5;
double arr[n];

I do not understand why the following compiles:

// Code 2
const int n = 5;
double arr[n]; // n is not a constant expression type!

Furthermore, if the compiler is smart enough to see that n is initialized with 5, then why does the following not compile:

// Code 3
int n = 5;
double arr[n]; // n is initialized with 5, so how is this different from Code 2?

P.S. This post answers using quotes from the standard, which I do not understand. I will very much appreciate an answer that uses a simpler language.

like image 962
AlwaysLearning Avatar asked Feb 27 '26 16:02

AlwaysLearning


1 Answers

n is not a constant expression type!

There is no such thing as a constant expression type. n in that example is a expression, and it is in fact a constant expression. And that is why it can be used as the array size.

It is not necessary for a variable to be declared constexpr in order for its name to be a constant expression. What constexpr does for a variable, is the enforcement of compile time constness. Examples:

int a = 42;

Even though 42 is a consant expression, a is not; Its value may change at runtime.

const int b = 42;

b is a constant expression. Its value is known at compile time

const int c = rand();

rand() is not a constant expression, and so c is neither. Its value is determined at runtime, but may not change after initialisation.

constexpr int d = 42;

d is a constant expression, just like b.

constexpr int f = rand();

Does not compile, because constexpr variables must be initialised with a constant expression.


then why does the following not compile:

Because the rules of the language don't allow it. The value of n is not compile time constant. The value of a non-const variable can change at runtime.

The language cannot have a rule that some value doesn't change at runtime, then it is a constant expression. That would not be of any use to the programmer since they cannot assume which compiler will be able to prove the constness of which variable.

The language has to exactly specify the cases where an expression is constant. It would also be infeasible to specify that a non-const variable is a constant expression if it hasn't been modified before its use, because it is impossible to prove in most cases, even though you've found one case where the proof happens to be easy.

like image 160
eerorika Avatar answered Mar 02 '26 06:03

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!