C++ - constexpr, consteval & Compile-time

Overview

Estimated time: 60–80 minutes

Push computation to compile time for speed and safety. Learn constexpr, consteval (immediate) functions, and constinit for globals.

Learning Objectives

  • Write constexpr functions usable at compile time and runtime.
  • Use consteval for values that must be computed at compile time.
  • Initialize globals with constinit to avoid static initialization order fiasco.

Prerequisites

constexpr function

constexpr int sq(int x){ return x*x; }
static_assert(sq(3)==9);
int main(){ int r = sq(5); (void)r; }

consteval (immediate) function

consteval int add_constexpr(int a,int b){ return a+b; }
constexpr int v = add_constexpr(2,3); // OK
// int x = add_constexpr(2,3); // error: not in constant evaluation

constinit

constinit int counter = 0; // must be initialized at compile time

Common Pitfalls

  • Assuming constexpr implies compile-time; it only enables—requires constant context.
  • Using consteval when runtime calls are intended—prefer constexpr in most APIs.

Checks for Understanding

  1. When does a constexpr function actually run at compile time?
  2. What does consteval guarantee?
Show answers
  1. When evaluated in a constant context (e.g., static_assert, template args, initializing a constexpr/constinit variable).
  2. The function can only be evaluated at compile time and cannot be called at runtime.

Exercises

  1. Write a constexpr factorial and verify with static_asserts.
  2. Use consteval to compute a checksum of a string literal at compile time.