`constexpr` — C++ Keyword

`constexpr` — C++ Keyword

The constexpr keyword in C++11: declares that a variable or function can be evaluated at compile time.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

constexpr

Specifies 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.

Syntax

constexpr Type name = expression;
constexpr return-type func(params) { body }
constexpr ClassName(params) { body }   // constexpr constructor

Example

#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
}

Notes

Example in practice

int 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;
}