Using normal functions in constant expressions gives compile time error as it can’t be run at compile time. We can use constexpr functions which can be used in constant expressions without giving compilation issues.
We can create constexpr function as shown below:
#include <iostream>
constexpr int max(int a, int b)
{
return a < b ? b : a;
}
int main(int argc, char const *argv[])
{
std::cout << max(1, 2);
return 0;
}A function has to follow below criteria to be a constexpr function:
- Its arguments must be known at compile time.
- All statements and expressions must be evaluatable at compile time.
Note
There are some other criteria which can be found here.
constexpr function can only call other constexpr functions. Failing to do so will give compile time error.
Things to Know of constexpr Functions
- They are implicitly inline.
As constexpr functions are evaluated at compile time, compiler has to have full function definition present in the translation unit. This means that multiple files should have the definition present in each translation unit, which would mean the violation of ODR. That’s why constexpr functions are implicitly inline. We can define constexpr functions in header files and use them.
- Forward declaration would not suffice for the function call. Function definition should be available before the call. However, if the
constexprfunction is called on non-constant-expression context, forward declaration should suffice.