`constexpr` — C++ Keyword
`constexpr` — C++ Keyword
The constexpr keyword in C++11: declares that a variable or function can be evaluated at compile time.
`constexpr` — C++ Keyword
The constexpr keyword in C++11: declares that a variable or function can be evaluated at compile time.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
constexprSpecifies that a variable's value or a function's result can (and, for variables, must) be computed at compile time when the inputs are constant expressions.
constexpr Type name = expression;
constexpr return-type func(params) { body }
constexpr ClassName(params) { body } // constexpr constructor
#include <print>
#include <array>
constexpr int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
constexpr double kPi = 3.14159265358979;
// constexpr member function
struct Circle {
double r;
constexpr double area() const { return kPi * r * r; }
};
int main() {
// Evaluated at compile time
constexpr int f5 = factorial(5); // 120
constexpr Circle c{3.0};
constexpr double a = c.area();
std::println("{}", f5); // 120
std::println("{:.4f}", a); // 28.2743
// Also usable at runtime
int n;
n = 6;
std::println("{}", factorial(n)); // 720 – evaluated at runtime
}
constexpr functions may also be called at runtime with non-constant arguments.consteval (C++20) is stricter: it requires compile-time evaluation.constexpr variables must be initialized with a constant expression.constexprint main() {
// Pick one facility from this reference page.
// Write the smallest program that exercises its main precondition,
// complexity rule, or lifetime constraint before scaling up.
return 0;
}