Module 6 · Generic code
6.4constexpr and consteval
Run your own functions while the program compiles. Write constexpr and consteval functions, start globals with constinit, pick template code with if constexpr, and build a lookup table that's ready before main starts.
On this page
- Key terms
- In 30 seconds
- constexpr functions: one function, two times
- consteval: compile time only
- constinit: a global that starts ready
- if constexpr: choosing code at compile time
- A lookup table built while compiling
- Undefined behavior is a compile error here
- Which one should I use?
- Under the hood
- Common pitfalls
- A constexpr variable needs constant inputs
- Keeping a std::vector as a constexpr variable
- Try it yourself
Key terms
- compile time and run time
- Compile time is while the compiler builds your program. Run time is later, while the program runs.
- constant expression
- An expression the compiler can work out at compile time. Only these can initialize a
constexprvariable, set an array size or go instatic_assert. - constant evaluation
- The compiler running your code at compile time to work out a constant expression.
constexprfunction- A function that can run at compile time when its arguments are constants and a constant result is needed, and at run time like any other function.
constevalfunction- A function that must run at compile time. Calling it with a value only known at run time doesn't compile.
constinit- On a global or
staticvariable: its first value must be worked out at compile time. Unlikeconstexpr, the variable can change later. if constexpr- An
ifwhose condition is decided at compile time. In a template, the branch that isn't taken is discarded and never compiled for that type. - lookup table
- An array of answers prepared in advance, so a question becomes an index: the code for base
'G'istable['G'].
Some answers never change: how many 3-letter DNA words there are, which 2-bit code belongs to each base, the size of a buffer. You could work them out by hand and type the numbers in, but then nothing checks them. C++ can run your own functions while it compiles, put the results straight into the program, and stop the build if a check fails or the calculation has a bug.
In 30 seconds
- A
constexprfunction runs at compile time when its result is needed as a constant, and at run time otherwise. - A
constevalfunction always runs at compile time; calling it with a run-time value is a compile error.constinitmakes a changeable global start from a compile-time value. if constexprpicks a branch at compile time, so a template can contain code that only compiles for some types.- Undefined behavior during compile-time evaluation, like signed overflow or reading past an array, is a compile error instead of a silent bug.
constexpr functions: one function, two times
Variables introduced constexpr variables, whose values are fixed at compile time. Put constexpr in front of a function, and the compiler can also run that function at compile time. Here kmer_count(k) is the number of DNA words of length k, 4 to the power k:
#include <array>
#include <print>
constexpr long long kmer_count(int k) {
long long n = 1;
for (int i = 0; i < k; ++i) {
n *= 4;
}
return n;
}
int main() {
constexpr long long codons = kmer_count(3);
static_assert(kmer_count(4) == 256);
std::array<int, kmer_count(2)> counts{};
int k = 11; // an ordinary variable
std::println("{} {} {}", codons, counts.size(), kmer_count(k));
}Output
64 16 4194304
The first three calls need a constant: a constexpr variable, a static_assert and the size of a std::array (a non-type template argument, from Class templates). So the compiler runs kmer_count at compile time and uses the result. The last call passes k, an ordinary variable, so it’s a normal call at run time. It’s the same function, and the body is written once.
A constexpr function can use local variables, loops, if and switch, and call other constexpr functions. When it runs at compile time, it can’t do anything that needs the running program: printing, reading input, or calling a function that isn’t constexpr.
Key ideaconstexpr means can, not must
constexpr on a function allows compile-time evaluation; it doesn’t force it. The standard only requires it where a constant is needed. Elsewhere, an optimizing compiler often works out kmer_count(3) early anyway, but that’s an optimization, not a promise.
consteval: compile time only
consteval is stricter: every call must be worked out at compile time. Use it for values that must never cost anything at run time, or for checks that must happen while compiling:
#include <print>
consteval long long kmer_count(int k) {
long long n = 1;
for (int i = 0; i < k; ++i) {
n *= 4;
}
return n;
}
int main() {
constexpr long long codons = kmer_count(3);
std::println("{} {}", codons, kmer_count(5));
}Output
64 1024
kmer_count(5) sits inside an ordinary std::println call, but 5 is a constant, so the compiler works it out and the program prints a fixed number. Pass a variable, and the call can’t happen at compile time:
#include <print>
consteval long long kmer_count(int k) {
long long n = 1;
for (int i = 0; i < k; ++i) {
n *= 4;
}
return n;
}
int main() {
int k = 5;
std::println("{}", kmer_count(k));
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:13:34: error: call to consteval function ‘kmer_count(k)’ is not a constant expression
13 | std::println("{}", kmer_count(k));
| ~~~~~~~~~~^~~
compilation terminated due to -fmax-errors=1.The fix is to make k itself constexpr int k = 5;, or, if k really comes from the running program, to make the function constexpr instead of consteval.
You’ve already used consteval without seeing it. Printing and reading showed that std::println checks its format string when you compile; the standard library does that check in a consteval function, which is why a format string must be known at compile time and can’t be a std::string built while the program runs.
constinit: a global that starts ready
A global variable lives in static storage, like the static locals from Stack, heap and lifetime, and is set up when the program starts. If its first value comes from an ordinary function, code runs at startup to compute it. constinit says the first value must be worked out at compile time instead, while the variable stays changeable:
#include <print>
constinit int reads_seen = 0;
void count_read() {
++reads_seen;
}
int main() {
count_read();
count_read();
std::println("{}", reads_seen);
}Output
2
constexpr int reads_seen wouldn’t work here, because a constexpr variable can’t change. If the first value can’t be worked out at compile time, constinit stops the build:
#include <print>
int default_min_quality() {
return 30;
}
constinit int min_quality = default_min_quality();
int main() {
std::println("{}", min_quality);
}The compiler rejects this
main.cpp:7:15: error: ‘constinit’ variable ‘min_quality’ does not have a constant initializer
7 | constinit int min_quality = default_min_quality();
| ^~~~~~~~~~~
compilation terminated due to -fmax-errors=1.Mark default_min_quality as constexpr, and it compiles. Why does it matter? Globals in different source files start up in an order the standard doesn’t fix, so one global’s startup code can read another that isn’t ready yet. A constinit global is ready before any code runs. Module 8 covers programs with several source files.
if constexpr: choosing code at compile time
In a template, an ordinary if still compiles both branches for every type. if constexpr decides at compile time and throws the other branch away, so it may contain code that wouldn’t compile for this type. This function uses std::integral from Concepts:
#include <concepts>
#include <print>
#include <string>
template <typename T>
void describe(const T& value) {
if constexpr (std::integral<T>) {
std::println("{} is a number", value);
} else {
std::println("{} has {} letters", value, value.size());
}
}
int main() {
describe(42);
describe(std::string{"GATTACA"});
}Output
42 is a number GATTACA has 7 letters
Remove constexpr, and describe<int> must compile value.size() too, even though that branch would never run:
#include <concepts>
#include <print>
#include <string>
template <typename T>
void describe(const T& value) {
if (std::integral<T>) {
std::println("{} is a number", value);
} else {
std::println("{} has {} letters", value, value.size());
}
}
int main() {
describe(42);
}The compiler rejects this
main.cpp: In instantiation of ‘void describe(const T&) [with T = int]’:
main.cpp:15:13: required from here
15 | describe(42);
| ~~~~~~~~^~~~
main.cpp:10:56: error: request for member ‘size’ in ‘value’, which is of non-class type ‘const int’
10 | std::println("{} has {} letters", value, value.size());
| ~~~~~~^~~~The condition of an if constexpr must be a constant expression: a concept, a constexpr variable, a sizeof. Outside a template, both branches are still checked, so if constexpr there only skips code that would compile anyway.
A lookup table built while compiling
Turning a DNA letter into its 2-bit code, as in Operators, is a question with 256 possible inputs, one for each char value. A lookup table answers it with one array read. A constexpr function builds the table, and a constexpr variable keeps the result, so the table is finished before the program starts:
#include <array>
#include <cstdint>
#include <limits>
#include <print>
#include <string>
constexpr std::uint8_t invalid = 0xFF;
constexpr std::array<std::uint8_t, 256> make_base_codes() {
std::array<std::uint8_t, 256> codes{};
codes.fill(invalid);
codes['A'] = 0b00;
codes['C'] = 0b01;
codes['G'] = 0b10;
codes['T'] = 0b11;
return codes;
}
constexpr auto base_code = make_base_codes();
static_assert(base_code['G'] == 0b10);
static_assert(base_code['N'] == invalid);
int main() {
std::string dna = "GATC";
std::uint8_t packed = 0;
for (char base : dna) {
packed = (packed << 2) | base_code[static_cast<unsigned char>(base)];
}
std::println("{} packed: {:08b}", dna, packed);
}Output
GATC packed: 10001101
codes.fill(invalid)sets all 256 entries to0xFF, a value no real code uses, so a letter likeNcan be spotted.static_assertchecks the finished table at compile time. Get a code wrong and the build stops.static_cast<unsigned char>(base)turns the letter into an index from 0 to 255. On this platformcharis signed, so a byte above 127 is a negativechar, which would otherwise become an index far past the end of the table.
The same pattern works for any small, fixed mapping: complements of bases, amino acids for codons, a table of powers.
Undefined behavior is a compile error here
At run time, signed overflow and reading past the end of an array are undefined behavior: nothing stops them unless a sanitizer is watching. During constant evaluation, the compiler is required to notice undefined behavior in the language itself, like these two. It makes the expression not a constant, and the build fails:
#include <print>
constexpr int square(int x) {
return x * x;
}
int main() {
constexpr int area = square(50'000);
std::println("{}", area);
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:8:32: in ‘constexpr’ expansion of ‘square(50000)’
main.cpp:4:14: error: overflow in constant expression [-fpermissive]
4 | return x * x;
| ~~^~~50'000 * 50'000 is 2.5 billion, more than an int holds. The same goes for an off-by-one loop, like the one in Control flow. <= reads one element past the end:
#include <print>
constexpr int sum_first(int n) {
int scores[3] = {7, 8, 9};
int total = 0;
for (int i = 0; i <= n; ++i) {
total += scores[i];
}
return total;
}
int main() {
constexpr int total = sum_first(3);
std::println("{}", total);
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:13:36: in ‘constexpr’ expansion of ‘sum_first(3)’
main.cpp:7:26: error: array subscript value ‘3’ is outside the bounds of array ‘scores’ of type ‘int [3]’
7 | total += scores[i];
| ~~~~~~~~^
main.cpp:4:9: note: declared here
4 | int scores[3] = {7, 8, 9};
| ^~~~~~That makes static_assert a cheap way to test a constexpr function: every test case runs inside the compiler, which catches mistakes like these without sanitizers. The protection covers only compile-time calls, though. Call square with a value read at run time, and it’s ordinary undefined behavior again, caught here by the sanitizer:
#include <iostream>
#include <print>
constexpr int square(int x) {
return x * x;
}
int main() {
int side = 0;
std::cin >> side;
std::println("{}", square(side));
}This fails when it runs
main.cpp:5:16: runtime error: signed integer overflow: 50000 * 50000 cannot be represented in type 'int'
Undefined behaviorconstexpr doesn't make a function safe
A constexpr function is checked only for the arguments you evaluate at compile time. Every other call follows the run-time rules. Undefined behavior collects the kinds and the tools that catch them.
Which one should I use?
Is it a value fixed in your code that never changes?
YesNoA
constexprvariableUsable instatic_assert, array sizes and template arguments.Is it a global or
staticvariable that changes while the program runs?YesNoconstinitIt starts from a compile-time value, with no startup code.Must every call of a function be worked out at compile time?
YesNoA
constevalfunctionA call with a run-time value doesn't compile.Is a function's result useful both at compile time and at run time?
YesNoA
constexprfunctionOtherwise: An ordinary function, and
constfor values only known at run time
| What | When | Why | How |
|---|---|---|---|
constexpr variable | Sizes, limits, tables: values fixed in the code. | Worked out once at compile time; usable wherever a constant is required. | constexpr int k = 3; |
constexpr function | A calculation you need both as a constant and with run-time values. | One function, written once, for both. | constexpr long long kmer_count(int k) |
consteval function | Results that must never be computed at run time. | The compiler rejects any call it can’t finish at compile time. | consteval long long kmer_count(int k) |
constinit | A global or static variable that changes, but must start ready. | No startup code, so no startup-order surprises. | constinit int reads_seen = 0; |
if constexpr | A template needs different code for different kinds of type. | The branch not taken isn’t compiled for that type. | if constexpr (std::integral<T>) |
Rule of thumb: make fixed values constexpr, make small pure functions constexpr and test them with static_assert, and reach for consteval and constinit when “at compile time” must be a guarantee.
Under the hood
For constant evaluation, the compiler runs your function in a built-in interpreter that checks every step: each array read is in bounds, each int result fits, each object is alive. That’s why it catches the undefined behavior the processor itself wouldn’t. The result goes into the program as plain data. base_code above is 256 bytes stored in the executable, already filled in; no code builds it when the program starts.
Since C++20 the interpreter can even use heap memory, so a constexpr function can use a std::vector inside:
#include <print>
#include <vector>
constexpr int sum_of_squares(int n) {
std::vector<int> squares;
for (int i = 1; i <= n; ++i) {
squares.push_back(i * i);
}
int total = 0;
for (int s : squares) {
total += s;
}
return total;
}
int main() {
static_assert(sum_of_squares(3) == 14);
constexpr int total = sum_of_squares(10);
std::println("{}", total);
}Output
385
The rule is that everything allocated during the evaluation must be freed before it ends. The vector is destroyed when the function returns, so only the int is left.
PerformanceCompile-time work makes builds slower
The interpreter is usually much slower than running the same code in your program, and compilers stop after a set number of steps (GCC’s -fconstexpr-ops-limit, Clang’s -fconstexpr-steps). Tables of a few thousand entries are fine; don’t try to precompute megabytes.
Common pitfalls
A constexpr variable needs constant inputs
A constexpr variable must be worked out at compile time, so everything in its initializer must be a constant too. An ordinary variable isn’t one, even if its value is written right there:
#include <print>
constexpr long long kmer_count(int k) {
long long n = 1;
for (int i = 0; i < k; ++i) {
n *= 4;
}
return n;
}
int main() {
int k = 3;
constexpr long long codons = kmer_count(k);
std::println("{}", codons);
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:13:45: error: the value of ‘k’ is not usable in a constant expression
13 | constexpr long long codons = kmer_count(k);
| ^
main.cpp:12:9: note: ‘int k’ is not const
12 | int k = 3;
| ^Make k constexpr too. If k comes from input, drop constexpr from codons and make it const: the function then runs at run time.
Keeping a std::vector as a constexpr variable
A std::vector can be used during constant evaluation, but its heap block can’t survive into the running program. GCC reports this from inside the standard library: the vector “refers to a result of operator new”, meaning memory from the heap.
#include <print>
#include <vector>
int main() {
constexpr std::vector<int> primes = {2, 3, 5, 7};
std::println("{}", primes);
}The compiler rejects this
In file included from /usr/include/c++/15/string:45,
from /usr/include/c++/15/bits/locale_classes.h:42,
from /usr/include/c++/15/locale:43,
from /usr/include/c++/15/format:49,
from /usr/include/c++/15/print:43,
from main.cpp:1:
/usr/include/c++/15/bits/allocator.h: In function ‘int main()’:
/usr/include/c++/15/bits/allocator.h:200:52: error: ‘std::vector<int>(std::initializer_list<int>{((const int*)(& const int [4]{2, 3, 5, 7})), 4}, std::allocator<int>())’ is not a constant expression because it refers to a result of ‘operator new’
| return static_cast<_Tp*>(::operator new(__n));
| ~~~~~~~~~~~~~~^~~~~When the size is fixed, use a std::array: constexpr std::array<int, 4> primes = {2, 3, 5, 7};. It holds its elements inside itself, so it can be a constant.
Try it yourself
Try it yourself
reverse_complement uses a switch to find each base’s partner (A with T, C with G). Replace complement with a 256-entry lookup table built by a constexpr function, with 'N' for every other character. Check the table with static_assert, for example that 'A' maps to 'T' and 'x' maps to 'N'.
#include <cstddef>
#include <print>
#include <string>
char complement(char base) {
switch (base) {
case 'A':
return 'T';
case 'C':
return 'G';
case 'G':
return 'C';
case 'T':
return 'A';
default:
return 'N';
}
}
std::string reverse_complement(const std::string& dna) {
std::string out;
for (std::size_t i = dna.size(); i > 0; --i) {
out += complement(dna[i - 1]);
}
return out;
}
int main() {
std::println("{}", reverse_complement("GATTACA"));
}Expected output
TGTAATC
Show a hint
Write constexpr std::array<char, 256> make_complements(), start from table.fill('N') and set the four letters. Keep the result in a constexpr variable, and index it with static_cast<unsigned char>(letter).
Show a solution
#include <array>
#include <cstddef>
#include <print>
#include <string>
constexpr std::array<char, 256> make_complements() {
std::array<char, 256> table{};
table.fill('N');
table['A'] = 'T';
table['C'] = 'G';
table['G'] = 'C';
table['T'] = 'A';
return table;
}
constexpr auto complements = make_complements();
static_assert(complements['A'] == 'T');
static_assert(complements['G'] == 'C');
static_assert(complements['x'] == 'N');
std::string reverse_complement(const std::string& dna) {
std::string out;
for (std::size_t i = dna.size(); i > 0; --i) {
out += complements[static_cast<unsigned char>(dna[i - 1])];
}
return out;
}
int main() {
std::println("{}", reverse_complement("GATTACA"));
}make_complements runs at compile time because its result initializes a constexpr variable, so the table is finished before main starts, and the static_asserts check it during the build. reverse_complement does one array read per base instead of a switch. The cast to unsigned char keeps the index between 0 and 255.
Saved in this browser only.