constexpr
constexpr specifies that the value of an object or a function can be evaluated at compile time and the expression can be used in other constant expressions. For example, in below code product() is evaluated at compile time.
// constexpr function for product of two numbers.
// By specifying constexpr, we suggest compiler to
// to evaluate value at compiler time
constexpr int product(int x, int y)
{
return (x * y);
}
int main()
{
const int x = product(10, 20);
cout << x;
return 0;
}
A function be declared as constexpr
- In C++ 11, a constexpr function should contain only one return statement. C++ 14 allows more than one statements.
- constexpr function should refer only constant global variables.
- constexpr function can call only other constexpr function not simple function.
- Function should not be of void type and some operator like prefix increment (++v) are not allowed in constexpr function.
https://www.geeksforgeeks.org/understanding-constexper-specifier-in-c/