constinit
- C++ course
- Expert
- Lesson 11/47
- 5 min
Learn constant initialization with C++20 constinit.
constinit
constinit (C++20) forces a variable with static or thread storage duration to be initialized at compile time. Example: constinit int counter = 10;.
Like constexpr it requires compile-time initialization; but it does not make the variable constant. So counter = 25; is valid. Use constinit for global counters, configuration values that start at compile time but may change later.
Static initialization guarantee
A global int counter = compute(); uses dynamic initialization; it calls compute() as the program starts. When dynamic initialization order across files is unclear, the static initialization order fiasco occurs.
A constinit int counter = 10; uses constant initialization; it is ready before the program starts. There is no ordering problem; the value is always fixed. This is why constinit is preferred for reliable global constants.
Practice Use the constinit counter
Define a global constinit int counter = 10;. In main assign counter = 25; and write std::cout << counter;.
Starter code
#include <iostream>
// Define the constinit counter variable here
int main() {
// Modify counter and print it
return 0;
}Sample solution
#include <iostream>
constinit int counter = 10;
int main() {
counter = 25;
std::cout << counter;
return 0;
}Expected output
25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the constinit declaration
constinit int counter = ____;
constinit int counter = 10;
Explanation: We initialize counter with 10.
2 Match each keyword to its trait
| Term | Meaning |
|---|---|
constinit int x = 5; |
Static, mutable |
constexpr int x = 5; |
Static, constant |
const int x = 5; |
Constant, no compile guarantee |
int x = 5; |
Run-time variable |
3 What does constinit allow that constexpr does not?
constinit int counter = 10;
int main() { counter = 25; }- Always compile time
- Becomes inline automatically
- Only inside classes
- Mutable at static storage Correct answer
Explanation: constinit is not constant; it initializes a static variable at compile time but allows later modification.