`constinit` — C++ Keyword

`constinit` — C++ Keyword

The constinit keyword in C++20: ensures a variable is initialized at compile time (but allows runtime modification).

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

constinit

Asserts that a variable with static or thread storage duration is initialized at compile time (constant initialization). Unlike constexpr, the variable itself is not const and may be modified at runtime. Introduced in C++20.

Syntax

constinit Type name = constant-expression;
constinit thread_local Type name = constant-expression;

Example

#include <print>

constinit int g_version = 2;          // initialized at compile time
constinit thread_local int tl_id = 0; // each thread starts at 0

// constinit const int kMax = 100;    // valid; combines constinit + const

int increment_version() {
    return ++g_version;   // runtime modification is fine
}

int main() {
    std::println("{}", g_version);           // 2
    std::println("{}", increment_version()); // 3
    std::println("{}", increment_version()); // 4
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}