`constinit` — C++ Keyword
`constinit` — C++ Keyword
The constinit keyword in C++20: ensures a variable is initialized at compile time (but allows runtime modification).
`constinit` — C++ Keyword
The constinit keyword in C++20: ensures a variable is initialized at compile time (but allows runtime modification).
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
constinitAsserts 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.
constinit Type name = constant-expression;
constinit thread_local Type name = constant-expression;
#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
}
constinit guarantees initialization before any dynamic initialization runs.const for true compile-time constants, or use without const for mutable globals with safe initialization.constinitint 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;
}