C++ 14 – relaxations for constexpr
You can use constexpr to define a constant expression since C++ 11. The expression is evaluated at compile-time and hence boosts performance.
C++ 14 introduced more features in terms of relaxations for constexpr. Let us see them one by one.
constexpr allows control structures
In C++ 11, only single expressions were allowed in constexpr, but in C++ 14, we can use if, switch, and loops such as for and while. Below is a table showing the difference across factorial calculation code across C++ 11 and C++ 14.
//C++ 11 code snippet
constexpr int factorial(int n) {
return (n <= 1) ? 1 : (n * factorial(n - 1));
}
//C++ 14 code snippet
constexpr int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
constexpr allows mutable variables
From C++ 14 onwards, non-const local variables are allowed inside constexpr. The only rule is that the values of the variables should not change after initialization.
//C++ 11 code snippet
// Not allowed: mutable variable inside constexpr function
constexpr int func(int n) {
int x = n; // Error
return x;
}
//C++ 14 code snippet
// Allowed: x should not change values after initialization
constexpr int func(int n) {
int x = n; // Allowed
return x;
}
Multiple return statements are allowed
In C++ 11, only a single return statement was allowed. It mainly was nested ternary conditional statements. From C++ 14 onwards, nested if and else statements are allowed inside constexpr. See below the differences in terms of code snippets.
// C++ 11 code snippet
constexpr int func(int n) {
return (n > 0) ? 1 : ((n < 0) ? -1 : 0);
}
// C++ 14 code snippet
constexpr int func(int n) {
if (n > 0) {
return 1;
} else if (n < 0) {
return -1;
} else {
return 0;
}
}