constexpr functions
suggest changeA function that is declared constexpr is implicitly inline and calls to such a function potentially yield constant expressions. For example, the following function, if called with constant expression arguments, yields a constant expression too:
constexpr int Sum(int a, int b)
{
return a + b;
}
Thus, the result of the function call may be used as an array bound or a template argument, or to initialize a constexpr variable:
int main()
{
constexpr int S = Sum(10,20);
int Array[S];
int Array2[Sum(20,30)]; // 50 array size, compile time
}
Note that if you remove constexpr from the declaration of Sum, assignment to S will not work, as S is a constexpr variable and must be initialized by a constant expression. Similarly, the array size will not be a constant expression if Sum is not constexpr.
A constexpr function can also be called like an ordinary function:
int a = 20;
auto sum = Sum(a, abs(-20));
Sum is still a constexpr function. This call is not a constant expression, because a is not one, so it runs at runtime. You do not need to write two functions. Until C++23, std::abs is not constexpr either.
Initializing a constexpr variable from that call will not compile:
int a = 20;
constexpr auto sum = Sum(a, abs(-20));
The reason is simple: a constexpr variable must be initialized by a constant expression, and this call is not one.
In C++11, the body of a constexpr function is essentially a single return statement, so the following is ill-formed. Since C++14, a local variable is allowed. The call is a constant expression only when its arguments are:
constexpr int Sum(int a, int b)
{
int a1 = a; // Error in C++11; allowed since C++14
return a + b;
}
Making a1 itself constexpr does not work. A function parameter is not a constant expression, so it cannot initialize a constexpr variable:
constexpr int Sum(int a, int b)
{
constexpr int a1 = a; // ERROR
// ...
Furthermore, the following will also not compile:
constexpr int Sum(int a, int b)
{
return abs(a) + b; // or abs(a) + abs(b)
}
Until C++23, std::abs is not constexpr, so abs(a) is not a constant expression. Even abs(10) does not qualify before that.
What about this?
constexpr int Abs(int v)
{
return v >= 0 ? v : -v;
}
constexpr int Sum(int a, int b)
{
return Abs(a) + b;
}
We crafted our own Abs function which is a constexpr, and the body of Abs also doesn’t break any rule. Also, at the call site (inside Sum), the expression evaluates to a constexpr. Hence, the call to Sum(-10, 20) will be a compile-time constant expression resulting to 30.