All Recipes
Home/Other Features/consteval and constinit
intermediate

consteval and constinit

Enforce compile-time evaluation and initialization

Example Code

cpp
#include <iostream>
// consteval: MUST be evaluated at compile time
consteval int square(int n) {
return n * n;
}
// constexpr: CAN be evaluated at compile time
constexpr int cube(int n) {
return n * n * n;
}
// constinit: must be initialized at compile time
// but can be modified at runtime
constinit int global_value = square(5); // OK: compile-time init
// Useful for avoiding static initialization order fiasco
constinit const char* app_name = "MyApp";
// consteval for compile-time only computation
consteval auto create_lookup_table() {
std::array<int, 10> table{};
for (int i = 0; i < 10; ++i) {
table[i] = i * i;
}
return table;
}
constexpr auto squares_table = create_lookup_table();
int main() {
constexpr int a = square(5); // OK: compile-time
// int x = 5;
// int b = square(x); // ERROR: x not constexpr
int y = 3;
int c = cube(y); // OK: runtime evaluation
constexpr int d = cube(4); // OK: compile-time
std::cout << "square(5) = " << a << std::endl; // 25
std::cout << "cube(3) = " << c << std::endl; // 27
// constinit variable can be modified
global_value = 100;
std::cout << "global = " << global_value << std::endl;
// Use lookup table
std::cout << "squares[7] = " << squares_table[7] << std::endl; // 49
return 0;
}

Explanation

consteval ensures functions are always evaluated at compile time. constinit ensures variables are initialized at compile time, preventing the static initialization order fiasco while still allowing runtime modification.

Key Points

  • 1consteval = always compile-time
  • 2constinit = compile-time initialization
  • 3constinit variables can change at runtime
  • 4Prevents static init order issues