Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A constexpr function is not required to return a constant expression?

Tags:

c++

c++11

C++ Primer (5th edition) on page 240 has a note stating:

"A constexpr function is not required to return a constant expression".

A question has been asked about this: can constexpr function return type be a non const?. The author of that question misunderstood the note.

But what is the correct understanding of it (the answers to the cited post clarify the confusion of that post's author, but do not answer my question)?

like image 707
AlwaysLearning Avatar asked Jul 03 '15 12:07

AlwaysLearning


People also ask

Are constexpr functions const?

All constexpr variables are const . A variable can be declared with constexpr , when it has a literal type and is initialized. If the initialization is performed by a constructor, the constructor must be declared as constexpr .

Is not usable as a constexpr function because?

It means that compiler can't guarantee that your if-constexpr is always compile-time, hence the error about it. If you place all your arguments as template auto parameters of your function then it should compile well.

What is constexpr used for?

constexpr stands for constant expression and is used to specify that a variable or function can be used in a constant expression, an expression that can be evaluated at compile time. The key point of constexpr is that it can be executed at compile time.

Is constexpr implicitly const?

In C++11, constexpr member functions are implicitly const.


1 Answers

A constexpr function must return* must have a path that returns a constant expression iff all parameters are constant expressions. This actually makes sense. Example:

constexpr int square(int i){
    return i*i;
}

std::array<int, square(2)> ia; //works as intended, constant expression
int i;
std::cin >> i;
int j = square(i); //works even though i is not a constant expression
std::array<int, square(i)> ia; //fails, because square does not (and cannot)
                               //return a constant expression

*Correction by chris.

like image 125
nwp Avatar answered Sep 28 '22 19:09

nwp