On this page
constexpr & consteval
Prev: auto | Up: builtins | Next: References & Rvalues
Rel: Templates, sizeof & alignof
Ref: cppreference — constexpr | cppreference — consteval
Tags: #public #prog #cpp #builtins #tier/core
Overview
constexpr allows variables, functions, and constructors to be evaluated at compile time (while still callable at runtime if given runtime arguments). consteval (C++20) defines an immediate function that must be evaluated at compile time—failing compilation otherwise.
Usage
constexpr int square(int x) { return x * x; }
consteval int must_compile_time(int x) { return x * 2; }
constexpr int a = square(8); // computed at compile time (64)
constexpr int b = must_compile_time(5); // guaranteed compile time (10)
// Compile-time branch elimination (C++17)
template <typename T>
auto stringify(const T& v) {
if constexpr (sizeof(T) <= 4) {
return static_cast<long>(v);
} else {
return v;
}
}
Notes
- Prefer
constexprover C#definemacros for typed, scoped constants. constinit(C++20) guarantees static initialization at compile time without making the variableconst, eliminating the static initialization order fiasco.
Linked from
Related notes
- tuts/cpp/builtins/auto Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/references_and_rvalues Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/sizeof_and_alignof Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins Linked here; links to this page; shared tags: #builtins, #cpp, #prog
- tuts/cpp/builtins/templates Linked here; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/c_style_casts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/casts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/classes_and_virtual shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/concepts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/lambdas shared tags: #builtins, #cpp, #prog, #tier