How do we understand "if possible" about constexpr

Viewed 134

I've read the link about constexpr: https://en.cppreference.com/w/cpp/language/constexpr

It says that the constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time.

As my understanding, it means that a variable specified by constexpr may or may not be evaluated at compile time.

This link told me the same thing: constexpr variables are not compile-time values.

However, I made a test, which confused me: https://godbolt.org/z/9ajb4xKK8

As you see, the variable a must be evaluated at compile time, otherwise it can't be used to declare an array. And the variable s can't be specified by constexpr because the constructor of std::string can't be invoked at compile time.

In a word, it seems that this testing is telling me that constexpr MUST evaluate the value at compile time. Otherwise, how can the variable a be used to declare an array?

What did I wrongly understand?

EDIT

I know that a constexpr function can be invoked at runtime or at compile time. For example, if we pass a runtime paramater to a constexpr function, the function would be invoked at runtime, I understand that.

But it seems that a constexpr variable MUST be evaluated at compile time. Can I say that any constexpr variable MUST be evaluated at compile time?

1 Answers

Firstly, the compiler used in your godbolt link (gcc 11.1) allows variable-length arrays. So a does not have to be a constant expression. i.e this snippet of code below will be accepted

int a = 5;
int arr[a];

But when you do need something to be a constant expression constexpr will allow you to use the variable/function in it.

constexpr - specifies that the value of a variable or function can appear in >constant expressions

For example, when you create an array using the std::array template, the size must be constant

So doing this is not OK

int a = 5;
std::array<int, a> arr;

On the other hand, constexpr allows a to be used in a constant expression, so you CAN do this

constexpr int a = 5;
std::array<int, a> arr;
Related