Constant Expression Functions
In C++11, constexpr functions were restricted to using very limited syntax. In C++14, support for constexpr functions has been expanded, including allowing the use of if statements and defining local variables within functions.
The main limitations include
- Only allowing a single return statement. In other words, a function can have only one return statement.
- Not allowing the declaration of local variables inside the function body.
- Not allowing the use of loops, recursion, or other complex control structures. These limitations restrict
constexprfunctions in C++11 to very simple calculations and operations and prevent them from handling complex logic and algorithms.
Let’s see some code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
// Define a constexpr function to calculate the absolute value of a given number
constexpr int abs(int x) {
if (x < 0) {
return -x;
} else {
return x;
}
}
int main() {
constexpr int num = -10;
constexpr int result = abs(num); // Calculate the absolute value at compile time
std::cout << "Absolute value: " << result << std::endl;
return 0;
}
In the above example, constexpr function uses if statement and two return statements, which were not allowed in C++11!!! It would result in errors.
Changing the language version to C++14 or above will yield the correct result.


