☕ Buy Me Coffee
← Back to Feed

constexpr vs const: Compile-Time Power

The constexpr specifier (since C++11) declares that it is possible to evaluate the value of the function or variable at compile time.

constexpr Variables

A constexpr variable must be initialized immediately and the initializer must be a constant expression.

constexpr int MaxSize = 100;
int arr[MaxSize]; // OK: MaxSize is compile-time constant

constexpr Functions

A function can be marked constexpr if it only contains constructs permitted in constant expressions. In C++11, these were very limited (essentially just a return). C++14/17/20 significantly relaxed these rules to allow loops, switch statements, and even dynamic allocation (C++20).

constexpr int factorial(int n) {
    return n <= 1 ? 1 : n * factorial(n - 1);
}
// This value is computed by the compiler:
constexpr int val = factorial(5); // val is 120

consteval (C++20)

Guarantees that the function must be executed at compile time. It produces an error if the result is used where a runtime value is expected.

// FEEDBACK_LOOP.exe

0.0 / 5.0
FROM 0 PEERS
→ Login to rate