Table of Contents

C++ constexpr

constexpr marks a function, variable, or object as evaluable at compile time. A constexpr function can be called with compile-time constants to produce compile-time results, or with runtime values to execute as normal code. Variables declared constexpr are constants evaluated during compilation.

Use constexpr to enable compile-time computation and improve performance by eliminating runtime work.

Example

This example shows compile-time computation and how constexpr functions adapt to compile-time and runtime contexts.

// compile: g++ -std=c++17 -o constexpr_ex constexpr_ex.cpp
// run: ./constexpr_ex
// description: constexpr functions evaluated at compile time or runtime
 
constexpr int factorial(int n) {
    return n <= 1 ? 1 : n * factorial(n - 1);
}
 
constexpr int compile_time = factorial(5);  // computed at compile time
 
int main() {
    constexpr int ct = factorial(5);  // compile time: 120
    int x = 5;
    int rt = factorial(x);  // runtime: 120
 
    return ct == rt ? 0 : 1;
}