Skip to content

constexpr (C++11) ​

In a nutshell ​

Tells the compiler "this value or function is capable of being computed at compile time," which moves runtime computations to compile time and gives you complex logic with zero runtime overhead.

Header file ​

None (language keyword)

Core API Cheat Sheet ​

OperationSignatureDescription
Compile-time variableconstexpr T var = expr;Requires expr to be a constant expression; the variable is implicitly const
Compile-time functionconstexpr T func(params);Evaluated at compile time when given constant arguments; otherwise degrades to an ordinary function
Compile-time constructorconstexpr T::T(params);Allows constructing objects of literal types inside constant expressions
Compile-time destructorconstexpr T::~T();(C++20) Allows destroying objects inside constant expressions
Feature-test macro__cpp_constexprDetects the current compiler's level of constexpr support

Minimal Example ​

C++
// Standard: C++14
#include <iostream>

constexpr int factorial(int n) {
    int res = 1;
    while (n > 1) res *= n--;
    return res;
}

int main() {
    constexpr int val = factorial(5); // Compile-time evaluation
    std::cout << val << '\n';         // Output: 120
    int k = 4;
    std::cout << factorial(k) << '\n';// Runtime evaluation: 24
}

Embedded Applicability: High ​

  • Moves computations such as lookup tables, CRC checks, and protocol parsing to compile time, consuming no Flash/RAM space
  • Values computed at compile time can be used directly as template arguments (e.g., array sizes), meeting the static-configuration needs of bare-metal environments
  • More readable and easier to debug than C macros or template metaprogramming
  • Note that C++11 imposes many restrictions (single return statement); for embedded projects we recommend at least the C++14 standard

Compiler Support ​

GCCClangMSVC
4.63.119.0

See Also ​


Part of the content is referenced from cppreference.com and is licensed under CC-BY-SA 4.0

pdf-latest-4-g85128cc · 85128cc · 2026-10-05