--- title: "constexpr in C++" description: "How constexpr moves work to compile time in C++11/14/17: constexpr functions, compile-time vs runtime evaluation, and why it beats template metaprogramming." date: 2023-04-06 last_modified_at: 2026-10-02 keywords: [C++, constexpr, compile-time computation, C++14, C++17] --- # Constexpr in C++ The `constexpr` keyword was introduced in C++11 and enhanced in C++14 and C++17. It enables computations to be performed at compile time. ## Basic Usage A `constexpr` function can be evaluated at compile time if its arguments are compile-time constants: ```cpp constexpr int square(int x) { return x * x; } // Used at compile time constexpr int result = square(5); // Computed during compilation // Used at runtime int input; std::cin >> input; int dynamic_result = square(input); // Computed at runtime ``` ## Constexpr vs Template Metaprogramming While template metaprogramming also enables compile-time computation, `constexpr` provides a more readable and maintainable approach: ```cpp // Fibonacci with constexpr (C++14 and later) constexpr int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n-1) + fibonacci(n-2); } // Usage constexpr int fib10 = fibonacci(10); // Computed at compile time ``` The advantage of `constexpr` over template metaprogramming is that it uses familiar function syntax rather than recursive template instantiations, making the code easier to understand and maintain.