Skip to content

constexpr (C++11)

In a Nutshell

Tells the compiler "this value or function has the ability to be evaluated at compile time," thereby moving runtime calculations to compile time and achieving zero-overhead complex logic.

None (language keyword)

Core API Cheat Sheet

OperationSignatureDescription
Compile-time variableconstexpr T var = expr;Requires expr to be a constant expression; variable is implicitly const
Compile-time functionconstexpr T func(args);If arguments are constants, it is evaluated at compile time; otherwise, it falls back to a normal function
Compile-time constructionconstexpr T::T(args);Allows constructing literal type objects in constant expressions
Compile-time destructionconstexpr T::~T();(C++20) Allows destroying objects in constant expressions
Feature test macro__cpp_constexprDetects the current compiler's level of support for constexpr

Minimal Example

cpp
// Compile-time calculation
constexpr int fib(int n) {
    return (n <= 1) ? n : (fib(n - 1) + fib(n - 2));
}

int main() {
    // Calculated at compile time, result is embedded in the binary
    constexpr int result = fib(10);
    static_assert(result == 55, "fib(10) should be 55");
    return 0;
}

Embedded Applicability: High

  • Moves calculations like table lookups, CRC checks, and protocol parsing to compile time, consuming no Flash/RAM space.
  • Values calculated at compile time can be used directly as template parameters (e.g., array sizes), satisfying static configuration needs in bare-metal environments.
  • Offers better code readability and debugging experience compared to C macros and template metaprogramming.
  • Note that C++11 has many restrictions (single return statement); we recommend using at least the C++14 standard for embedded projects.

Compiler Support

GCCClangMSVC
4.63.119.0

See Also


Part of the content references cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05