Logo
Articles Compilers Libraries Books MiniBooklets Assembly C++ Rust Go Linux CPU Others Videos
Advertisement

Article by Ayman Alheraki on March 28 2026 10:58 PM

Understanding constinit in C++20 Guaranteed Constant Initialization

Understanding constinit in C++20: Guaranteed Constant Initialization

C++20 introduces a new keyword, constinit, to help developers safely initialize global or static variables. But it’s often misunderstood, so let’s break it down.

What is constinit?

constinit is used to ensure a variable is initialized at compile-time or program startup, but unlike const or constexpr, the variable itself can still be modified later.

Think of it as a guarantee of initialization, not immutability.

Key Points:

  • Guarantees static initialization at compile-time (for global/static variables).

  • Can only be used on non-local variables (globals, namespace-scope, or static members).

  • The variable is not constant; you can change it after initialization.

  • Helps prevent the “static initialization order fiasco” in C++.

constinit vs const vs constexpr

KeywordCompile-time InitCan Modify LaterNotes
constYesNoImmutable after initialization
constexprYesNoMust be compile-time constant
constinitYesYesGuarantees initialization, but mutable

constinit does not make a variable constant. It just ensures it is initialized before use, especially important for global or static variables.

Example 1: Basic Usage

Output:

Here, constinit guarantees that counter is initialized at program startup. Later, we can still modify its value.

Example 2: Avoiding Static Initialization Order Problems

A common C++ issue is the static initialization order fiasco, where the order of global/static variable initialization across translation units is undefined. constinit helps catch errors at compile-time if a variable might not be safely initialized.

Without constinit, you might accidentally write a static variable that depends on another static variable in another file, causing undefined behavior. constinit forces the compiler to check.

Important Notes

  1. Cannot use constinit with local variables:

  1. Works with inline variables to ensure single initialization across multiple translation units.

  2. Can be combined with constexpr but rarely needed, because constexpr already guarantees compile-time initialization.

Why Use constinit?

  • Ensures safety for global and static variables.

  • Prevents subtle runtime bugs caused by uninitialized or misordered variables.

  • Still allows mutable behavior, unlike const.

In short: constinit = “initialized correctly, but can change later.”

Advertisements

Responsive Counter
General Counter
1195552
Daily Counter
2603