C++ - constint

less than 1 minute read

C++20 introduced the constinit which will initialize the value at compile time but still you can modify it at runtime

📝 Difference from constexpr

Keyword Compile-time init Constant after init Usable in constant expressions
constexpr
constinit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

constinit int global_id = 42;  // Compile-time initialized

int get_initial_value() {
    return 100;
}

// This would be an error because get_initial_value() is not constexpr
// constinit int another = get_initial_value(); // ❌ Error

int main() {
    std::cout << "global_id = " << global_id << "\n";

    // You can still modify it
    global_id += 1;
    std::cout << "global_id (after increment) = " << global_id << "\n";

    return 0;
}

Categories:

Updated: