constinit Specifier in C++ 20 (original) (raw)

Last Updated : 10 Jun, 2026

The constinit specifier was introduced in C++20 to guarantee that variables with static or thread storage duration are initialized before program execution begins.

#include using namespace std;

// Declare a constinit variable constinit int x = 42;

int main() { cout << "x = " << x << endl; return 0; }

`

**Output

x = 42

**Explanation

Syntax

constinit T variable = initializer;

**Where:

Rules and Restrictions of constinit

The constinit specifier has the following requirements:

**Note: Unlike constexpr, constinit only guarantees initialization at compile time; it does not require the variable to remain constant throughout the program.

Example: constinit with constexpr

The following code is invalid because constinit and constexpr cannot be used together.

C++ `

#include using namespace std;

// Error: constinit cannot be used with constexpr constinit constexpr int x = 42;

int main() { cout << x << std::endl; return 0; }

`

**Error

Example: constinit with consteval

The following code is invalid because constinit applies to variables, whereas consteval applies to functions.

C++ `

#include using namespace std;

// Error: constinit cannot be used with consteval constinit consteval int square(int x) { return x * x; }

int main() { cout << square(5) << std::endl; return 0; }

`

**Error

Advantages of constinit

Using constinit provides the following benefits: