Work done by the compiler costs nothing at run time
If a value depends only on things known when the program is built (table contents, scaling constants, hashes of fixed strings, struct sizes), computing it at run time wastes cycles on every start or every call, and checking it at run time finds mistakes late. Modern C++ lets you write ordinary-looking code that the compiler executes:
| Tool | Meaning |
|---|---|
constexpr variable | must be initialised by a constant expression; evaluated at compile time |
constexpr function | may be evaluated at compile time; is when used where a constant is required |
consteval function (C++20) | must be evaluated at compile time ("immediate function") |
constinit variable (C++20) | static storage initialised at compile time, but mutable afterwards |
if constexpr | compile-time branch inside a template; the discarded branch is not instantiated |
static_assert | compile-time check with a message; costs nothing at run time |
The key subtlety: a constexpr function called with run-time arguments simply runs at run time. constexpr is permission, not a guarantee.
A worked program
#include <array>
#include <cstdint>
#include <cstdio>
#include <type_traits>
// 1. constexpr: may run at compile time; must when the result is needed as a constant.
constexpr std::int64_t pow10(int n) {
std::int64_t r = 1;
for (int i = 0; i < n; ++i) r *= 10;
return r;
}
// 2. A compile-time lookup table built by an ordinary loop.
constexpr auto kPow10 = [] {
std::array<std::int64_t, 19> t{};
for (int i = 0; i < 19; ++i) t[i] = pow10(i);
return t;
}();
static_assert(kPow10[18] == 1'000'000'000'000'000'000);
// 3. consteval: must run at compile time; a runtime argument is a compile error.
consteval std::uint32_t fnv1a(const char* s) {
std::uint32_t h = 2166136261u;
while (*s) { h ^= static_cast<unsigned char>(*s++); h *= 16777619u; }
return h;
}
// 4. if constexpr: the discarded branch is not instantiated for this T.
template <class T>
double to_double_price(T raw, int decimals) {
if constexpr (std::is_integral_v<T>) {
return static_cast<double>(raw) / static_cast<double>(kPow10[decimals]); // fixed-point ticks
} else {
static_assert(std::is_floating_point_v<T>, "price must be integral ticks or floating point");
return static_cast<double>(raw);
}
}
struct alignas(64) Quote { std::int64_t bid, ask; std::int32_t bid_qty, ask_qty; };
static_assert(sizeof(Quote) == 64, "Quote must fill exactly one 64-byte line");
static_assert(std::is_trivially_copyable_v<Quote>, "Quote is memcpy'd into a shared-memory ring");
int main(int argc, char**) {
constexpr auto h = fnv1a("AAPL"); // computed by the compiler
std::printf("fnv1a(\"AAPL\") = %u\n", h);
switch (fnv1a("MSFT")) { // case labels need constants: consteval provides them
case fnv1a("AAPL"): std::puts("AAPL"); break;
case fnv1a("MSFT"): std::puts("MSFT"); break;
default: std::puts("other");
}
std::printf("%.4f %.4f\n", to_double_price(std::int64_t{1234567}, 4), to_double_price(123.4567, 4));
std::printf("pow10(argc + 2) at runtime = %lld\n", static_cast<long long>(pow10(argc + 2)));
}
Run with no arguments (argc is 1):
fnv1a("AAPL") = 1489842955
MSFT
123.4567 123.4567
pow10(argc + 2) at runtime = 1000
What each part shows:
- Lookup table:
kPow10is built by an immediately invoked lambda with a normalforloop and lands in read-only data. No start-up code, no initialisation-order problems. The same pattern builds CRC tables, bit-count tables, or a price-to-tick map for a fixed tick schedule. - consteval hashing: switching on strings is impossible in C++, but switching on their compile-time hashes is not. Because
fnv1aisconsteval, the case labels are guaranteed constants and the run-time code is an integer comparison. (A real dispatcher must handle collisions: the compiler rejects duplicate case labels, so a collision among the labels is caught at build time, but an unknown input that hashes to a label is not; compare the string after matching.) The value 1489842955 was cross-checked with an independent Python implementation of 32-bit FNV-1a. - if constexpr:
to_double_price<int64_t>compiles only the division branch,to_double_price<double>only the pass-through. With a plainif, both branches must compile for everyT. - static_assert on layout: if someone adds a field to
Quote, the build fails with the message, instead of a shared-memory reader on another process silently misreading bytes. - Same function at run time:
pow10(argc + 2)depends on a run-time value, so it runs normally.constexprdid not make it compile-time.
The compiler as a bug detector
Constant evaluation is stricter than run time: undefined behaviour is a compile error during constant evaluation. Calling a consteval function with a run-time value is also an error. This file does both:
#include <cstdint>
consteval std::uint32_t square(std::uint32_t x) { return x * x; }
constexpr int bad_pow10(int n) { int r = 1; for (int i = 0; i < n; ++i) r *= 10; return r; }
int main(int argc, char**) {
constexpr int ok = bad_pow10(9);
constexpr int overflow = bad_pow10(10); // int overflow: UB is a compile error in constant evaluation
return static_cast<int>(square(argc)) + ok + overflow; // runtime argument to consteval
}
Clang 17 rejects it (abridged):
ct_err.cpp:6:19: error: constexpr variable 'overflow' must be initialized by a constant expression
ct_err.cpp:3:75: note: value 10000000000 is outside the range of representable values of type 'int'
ct_err.cpp:7:29: error: call to consteval function 'square' is not a constant expression
ct_err.cpp:7:36: note: function parameter 'argc' with unknown value cannot be used in a constant expression
2 errors generated.
bad_pow10(9) fits in a 32-bit int (maximum ); does not. At run time that overflow would be silent undefined behaviour; at compile time it is a diagnostic. This makes static_assert over constexpr functions a cheap unit-testing tool: static_assert(round_to_tick(100.07, 0.05) == ...) runs the test on every build.
Worked example
a compile-time tick table, and when not to bother
A venue's tick size depends on price band: 0.01 below 10, 0.05 from 10 to below 100, 0.10 from 100 upward. Prices are stored as integer hundredths. Design a compile-time-checked way to validate that an order price is on a tick, and say what you would not move to compile time.
Show solutionHide solution
In hundredths, the tick sizes are 1, 5 and 10, with band boundaries at 1000 and 10000. Encode the schedule as a constexpr array of {lower_bound, tick} pairs and write a constexpr function on_tick(p) that finds the band and returns p % tick == 0. Then pin the behaviour with static_asserts that run on every build:
on_tick(999): band 1 (tick 1), , true.on_tick(1002): band 2 (tick 5), , false.on_tick(1005): , true.on_tick(10005): band 3 (tick 10), , false.
At run time the same function validates live orders with a few comparisons and one modulo, with no table construction at start-up, and a static_assert that the bounds are strictly increasing catches a mis-edited schedule at build time.
What not to move to compile time: anything that changes without a rebuild. If the venue publishes tick schedules in a reference-data file that can change daily, a compile-time table forces a redeploy for a data change, which is an operational risk. Load it at start-up into a flat array instead. Compile-time tables are for things that are truly fixed (mathematical constants, protocol layouts, hashes of fixed message-type names).
Trade-offs to state in an interview
- Build time: heavy constant evaluation and template instantiation slow compiles, and compilers cap constant-evaluation steps (
-fconstexpr-stepsin Clang). A 10-second build added to every developer's edit loop has a real cost. - Code size: every distinct template instantiation is a separate function.
if constexprand templates on many types can bloat the instruction cache, which can cost more than the branch you removed. - Debuggability: you cannot step through constant evaluation in a debugger; errors arrive as compiler diagnostics, sometimes deep inside templates. Keep compile-time functions small and also callable at run time so you can test them normally.
- Flexibility: a compile-time value requires a rebuild to change. Decide deliberately what is a constant and what is configuration.
The usual interview prompt is "how would you remove this run-time branch or table lookup?". A good answer moves only what is genuinely fixed, guards layout and protocol assumptions with static_assert, and mentions the build-time and code-size costs.
Knowledge check
A constexpr function is called with an argument read from a config file at start-up. When is it evaluated?
Knowledge check
Inside a function template, what does if constexpr give you that a plain if on std::is_integral_v<T> does not?
Knowledge check
During constant evaluation, a constexpr function overflows a signed int. What happens?
Key takeaways
constexprmeans "may run at compile time";constevalmeans "must";constinitmeans "initialised at compile time, mutable later".- Build fixed lookup tables with ordinary loops in
constexprlambdas: they go into read-only data with no start-up cost. if constexprselects code per type and discards the other branch before it is instantiated.static_assertdocuments and enforces layout, size and arithmetic assumptions on every build; UB in constant evaluation is a compile error.- Pay for compile-time work with build time, code size and debuggability; move only what is genuinely fixed.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).