Table of Contents
A constexpr function is a function that can be evaluated at compile time when it is called with arguments that permit constant evaluation. The constexpr specifier indicates that the function is intended to be usable in constant expressions.
A constexpr function can also be called at runtime when its arguments or context do not permit compile-time evaluation. This allows the same function to be used in both compile-time and runtime contexts.
Source Code #
#include <iostream>
constexpr int square(int number)
{
return number * number;
}
int main()
{
constexpr int result = square(5);
std::cout << "Square: " << result << '\n';
return 0;
}
Output #
Square: 25
Explanation #
- The
constexprspecifier declaressquare()as a function that can participate in constant evaluation. square()accepts anintparameter and returns anint.return number * number;calculates the square of the supplied value.constexpr int result = square(5);requiressquare(5)to produce a constant expression becauseresultis declaredconstexpr.- The compiler can evaluate
square(5)during compilation. - A
constexprfunction is not restricted to compile-time execution; it can also be called at runtime when compile-time evaluation is not possible or required. - The rules governing what a
constexprfunction may contain have expanded across successive C++ standards. return 0;terminates the program successfully.