Ask the compiler to do the work, so the program does not have to.
The Analogy: Cut at the Factory, Not in the Shop
A hardware shop that sells timber can do the cutting in two places. It can keep full-length planks and cut each one while the customer waits — flexible, but every customer pays the same few minutes. Or it can have the mill cut the common sizes before the timber ever reaches the shelf, so the customer picks up a finished piece and walks out.
Compilation is the mill. If a value can be worked out from information already available while the program is being built — a table of constants, the size of a buffer, a checksum polynomial, the result of a formula over fixed inputs — then computing it at run time is doing shop-floor work that the mill could have finished for free. constexpr is how you tell the compiler that a value or a function is eligible for the mill.
Two things follow, and the second is the more valuable. The obvious one is speed: work moved to compile time costs the running program nothing. The subtler one is certainty — anything the compiler can compute, it can also check. A bad table entry or an impossible size stops the build instead of shipping.
Syntax or Core Structure
#include <iostream>
#include <array>
#include <string_view>
// 1. A constant known at compile time.
constexpr int kMaxUsers = 100;
// 2. A function that MAY run at compile time.
constexpr int square(int n) { return n * n; }
// 3. Loops, local variables and branches are all allowed (C++14 onwards).
constexpr int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; ++i) result *= i;
return result;
}
// 4. A literal type: constexpr constructor, constexpr member functions.
struct Point {
int x = 0, y = 0;
constexpr Point(int px, int py) : x(px), y(py) {}
constexpr int distanceSquared() const { return x * x + y * y; }
};
// 5. A whole table, built by a function, before the program runs.
constexpr std::array<int, 8> makePowers() {
std::array<int, 8> t{};
for (int i = 0; i < 8; ++i) t[i] = 1 << i;
return t;
}
constexpr auto kPowers = makePowers();
// 6. constexpr static members need no out-of-line definition (C++17).
struct Limits {
static constexpr int kRetries = 3;
static constexpr std::string_view kName = "limits";
};
int main() {
// Checked by the compiler. No runtime cost, and no test to run.
static_assert(square(12) == 144);
static_assert(factorial(5) == 120);
static_assert(Point{3, 4}.distanceSquared() == 25);
static_assert(kPowers[7] == 128);
static_assert(Limits::kRetries == 3);
// Usable where only a constant will do.
int grid[kMaxUsers];
std::array<double, square(4)> matrix{};
std::cout << "grid " << sizeof(grid) / sizeof(grid[0])
<< ", matrix " << matrix.size() << "\n";
// The same functions run perfectly well at runtime.
int userCount = 7; // imagine this arrived from input
std::cout << "square(" << userCount << ") = " << square(userCount) << "\n";
std::cout << "factorial(" << userCount << ") = " << factorial(userCount) << "\n";
// constexpr variables are const: this would not compile.
// kMaxUsers = 200;
for (const int p : kPowers) std::cout << p << " ";
std::cout << "\n";
return 0;
}
Output:
grid 100, matrix 16
square(7) = 49
factorial(7) = 5040
1 2 4 8 16 32 64 128
Two lines carry most of the lesson. static_assert(factorial(5) == 120); ran a loop, at compile time, and produced no code — if the answer had been wrong the build would have failed with the assertion, not the tests. And factorial(userCount) called the same function with a value that does not exist until the program runs. That is the key idea: constexpr on a function is a permission, not a command. It says "this function is capable of compile-time evaluation", and the compiler uses that capability when the arguments allow it.
On a variable, constexpr is stricter. It is a requirement: the initialiser must be computable at compile time, and the variable is implicitly const.
Technical Depth: What Runs When
const versus constexpr versus the C++20 additions
| Keyword | Applies to | Means |
|---|---|---|
const | Variables, member functions | "Will not be modified through this name." Says nothing about when the value is known. |
constexpr (variable) | Variables | "Initialised at compile time." Implies const. |
constexpr (function) | Functions | "May be evaluated at compile time, if the arguments allow it." |
consteval (C++20) | Functions | "Must be evaluated at compile time." A runtime call is an error. |
constinit (C++20) | Static/thread-local variables | "Initialised at compile time, but not const afterwards." |
The const versus constexpr line is the one worth being precise about:
int runtimeValue();
const int a = 5; // compile-time constant, as it happens
const int b = runtimeValue(); // perfectly legal: const, but not a constant
constexpr int c = 5; // guaranteed compile-time
// constexpr int d = runtimeValue(); // ERROR
int array1[a]; // ok
// int array2[b]; // ERROR: b is not a constant expression
int array3[c]; // ok
Every constexpr variable is const; not every const variable is a constant expression.
Forcing compile-time evaluation
A constexpr function called with runtime values quietly runs at runtime. If you need the compile-time answer, put it somewhere only a constant will do:
constexpr int limit = factorial(5); // guaranteed compile-time
static_assert(factorial(5) == 120); // guaranteed compile-time
std::array<int, factorial(4)> buf{}; // guaranteed compile-time
template <int N> struct Tag {};
Tag<square(3)> t; // guaranteed compile-time
int n = 5;
int maybe = factorial(n); // definitely runtime
int probably = factorial(5); // usually folded, but not guaranteed
C++20 removes the guesswork:
consteval int mustBeCompileTime(int n) { return n * n; }
constexpr int ok = mustBeCompileTime(4);
// int bad = mustBeCompileTime(runtimeValue()); // ERROR, as intended
And std::is_constant_evaluated() lets one function take different paths:
constexpr double sqrtOf(double x) {
if (std::is_constant_evaluated())
return newtonIteration(x); // slow but constexpr-legal
else
return std::sqrt(x); // the fast intrinsic, at runtime
}
What a constexpr function may contain
The rules have loosened with every standard, which is why old advice about constexpr sounds far more restrictive than the reality:
| Feature | Allowed from |
|---|---|
A single return statement | C++11 |
Local variables, loops, if, multiple returns | C++14 |
switch, mutation of locals | C++14 |
try/catch blocks (not thrown during evaluation) | C++20 |
new / delete, if freed within the same evaluation | C++20 |
Virtual calls, dynamic_cast, typeid | C++20 |
std::vector and std::string in constant expressions | C++20 |
Uninitialised variables, goto | Still not allowed |
What remains forbidden is anything that reaches outside the evaluation: I/O, static local variables, reading a non-constexpr global, calling a non-constexpr function, and undefined behaviour of any kind. That last one is a gift — signed overflow or an out-of-bounds array index that would be silent UB at runtime is a hard compile error during constant evaluation.
constexpr int overflow() {
int x = 2147483647;
return x + 1; // UB at runtime; compile error in constexpr
}
// constexpr int boom = overflow(); // error: not a constant expression
C++20's allocation support is real but transient — anything allocated during constant evaluation must also be freed during it, so a constexpr function may use a std::vector internally and return a std::array, but cannot hand a std::vector back as a constexpr variable.
Literal types, and constexpr in classes
For an object to exist at compile time, its type must be a literal type: a constexpr constructor, a trivial destructor, and only literal-type members.
struct Version {
int major = 0, minor = 0;
constexpr Version(int ma, int mi) : major(ma), minor(mi) {}
constexpr bool atLeast(const Version& other) const {
return major > other.major || (major == other.major && minor >= other.minor);
}
};
constexpr Version kRequired{2, 4};
constexpr Version kCurrent{2, 7};
static_assert(kCurrent.atLeast(kRequired));
A class holding a std::string or a std::unique_ptr cannot be constexpr (before C++20 at all, and after it only within a single evaluation), because the destructor is not trivial. std::string_view and std::array are the constexpr-friendly substitutes.
if constexpr is a different tool
template <typename T>
std::string describe(const T& value) {
if constexpr (std::is_integral_v<T>)
return "integer " + std::to_string(value);
else if constexpr (std::is_floating_point_v<T>)
return "real " + std::to_string(value);
else
return "something else";
}
if constexpr discards the untaken branch before it is type-checked for instantiation, which is what makes it work where a plain if would not compile. It is about which code exists, whereas constexpr on a function or variable is about when a value is computed. The two are often used together and are not the same feature.
constexpr versus the alternatives
| Approach | Type-checked | Debuggable | Scoped | Verdict |
|---|---|---|---|---|
#define MAX 100 | No | No | No | Avoid in C++ |
enum { MAX = 100 }; | Integers only | Partly | Yes | Legacy; use constexpr |
const int MAX = 100; | Yes | Yes | Yes | Fine for local constants |
constexpr int MAX = 100; | Yes | Yes | Yes | Preferred |
| Template metaprogramming | Yes | Barely | Yes | Only where constexpr cannot reach |
| A hand-written lookup table | Yes | Yes | Yes | constexpr generates it instead |
The costs
constexpr is not free, it just moves the bill. Compile-time evaluation is interpreted by the compiler and is far slower per operation than the running program would be, so a table with a million entries can add seconds to every build. Large constexpr tables also live in the binary, trading executable size for startup time. And a function written to be constexpr-eligible sometimes has to avoid the clearest runtime implementation. Use it where the value is genuinely fixed, small enough to be worth embedding, and useful to have checked.
Real World Example: An LED Strip Palette Built at Compile Time
Firmware for an LED strip needs a gamma-correction table, a set of named colours, and a ramp between two of them. None of that depends on anything the program learns at run time, so all of it can be finished before the binary is written — and checked while it is.
#include <iostream>
#include <array>
#include <cstdint>
#include <stdexcept>
// A gamma-2.0 curve, computed once by the compiler.
constexpr std::array<std::uint8_t, 256> makeGammaTable() {
std::array<std::uint8_t, 256> table{};
for (int i = 0; i < 256; ++i)
table[i] = static_cast<std::uint8_t>((i * i) / 255);
return table;
}
constexpr auto kGamma = makeGammaTable();
static_assert(kGamma[0] == 0);
static_assert(kGamma[128] == 64);
static_assert(kGamma[255] == 255);
struct Colour {
std::uint8_t r = 0, g = 0, b = 0;
constexpr Colour() = default;
constexpr Colour(std::uint8_t red, std::uint8_t green, std::uint8_t blue)
: r(red), g(green), b(blue) {}
constexpr Colour corrected() const { return Colour{kGamma[r], kGamma[g], kGamma[b]}; }
constexpr Colour scaled(int percent) const {
return Colour{static_cast<std::uint8_t>(r * percent / 100),
static_cast<std::uint8_t>(g * percent / 100),
static_cast<std::uint8_t>(b * percent / 100)};
}
constexpr int luminance() const { return (r * 299 + g * 587 + b * 114) / 1000; }
};
// The throw is unreachable for valid input, so this stays usable at compile time.
constexpr Colour blend(Colour a, Colour b, int weight) {
if (weight < 0 || weight > 100)
throw std::out_of_range("blend weight must be 0..100");
return Colour{static_cast<std::uint8_t>((a.r * (100 - weight) + b.r * weight) / 100),
static_cast<std::uint8_t>((a.g * (100 - weight) + b.g * weight) / 100),
static_cast<std::uint8_t>((a.b * (100 - weight) + b.b * weight) / 100)};
}
constexpr Colour kWarmWhite{255, 200, 140};
constexpr Colour kCoolWhite{200, 220, 255};
constexpr Colour kMidpoint = blend(kWarmWhite, kCoolWhite, 50);
static_assert(kMidpoint.r == 227 && kMidpoint.g == 210 && kMidpoint.b == 197);
// constexpr Colour bad = blend(kWarmWhite, kCoolWhite, 150);
// error: the throw is reached, so this is not a constant expression
constexpr std::array<Colour, 5> makeRamp(Colour from, Colour to) {
std::array<Colour, 5> ramp{};
for (int i = 0; i < 5; ++i) ramp[i] = blend(from, to, i * 25);
return ramp;
}
constexpr auto kRamp = makeRamp(kWarmWhite, kCoolWhite);
static_assert(kRamp.front().r == 255);
static_assert(kRamp.back().b == 255);
// Wire format depends on a compile-time policy, not a runtime flag.
template <int Channels>
constexpr int packedSize(int pixels) {
if constexpr (Channels == 3) return pixels * 3;
else if constexpr (Channels == 4) return pixels * 4 + 1; // plus a trailing marker
else return pixels; // monochrome
}
static_assert(packedSize<3>(60) == 180);
static_assert(packedSize<4>(60) == 241);
static_assert(packedSize<1>(60) == 60);
int main() {
std::cout << "gamma table built at compile time: "
<< "kGamma[64]=" << +kGamma[64]
<< " kGamma[128]=" << +kGamma[128]
<< " kGamma[192]=" << +kGamma[192] << "\n\n";
std::cout << "ramp (a compile-time constant):\n";
for (const Colour& c : kRamp) {
const Colour out = c.corrected();
std::cout << " raw(" << +c.r << "," << +c.g << "," << +c.b << ")"
<< " gamma(" << +out.r << "," << +out.g << "," << +out.b << ")"
<< " lum=" << c.luminance() << "\n";
}
std::cout << "\n";
std::cout << "packed sizes: 3ch=" << packedSize<3>(60)
<< " 4ch=" << packedSize<4>(60)
<< " 1ch=" << packedSize<1>(60) << "\n\n";
int brightness = 40; // imagine a dial, read at runtime
const Colour dimmed = kMidpoint.scaled(brightness); // same function, runtime call
std::cout << "brightness " << brightness << "%: dimmed midpoint ("
<< +dimmed.r << "," << +dimmed.g << "," << +dimmed.b << ")\n";
return 0;
}
Output:
gamma table built at compile time: kGamma[64]=16 kGamma[128]=64 kGamma[192]=144
ramp (a compile-time constant):
raw(255,200,140) gamma(255,156,76) lum=209
raw(241,205,168) gamma(227,164,110) lum=211
raw(227,210,197) gamma(202,172,152) lum=213
raw(213,215,226) gamma(177,181,200) lum=215
raw(200,220,255) gamma(156,189,255) lum=218
packed sizes: 3ch=180 4ch=241 1ch=60
brightness 40%: dimmed midpoint (90,84,78)
The 256-byte gamma table exists in the binary as data. No loop runs at startup, and on a microcontroller with no floating-point unit that matters twice over — the curve was computed with the compiler's arithmetic, not the target's. makeGammaTable is an ordinary function containing an ordinary loop; the only thing that makes it a compile-time table is that its result was assigned to a constexpr variable, which is a requirement rather than a permission and would have failed the build if anything inside had not been evaluable.
Colour qualifies as a literal type because it has constexpr constructors, a trivial destructor, and members that are all literal types themselves. That is what allows kMidpoint to be a compile-time object rather than something assembled at startup. Had Colour carried a std::string name member, none of this would compile — a reminder that std::string_view and std::array are the constexpr-friendly choices.
The throw inside blend is the most interesting line in the file. A constexpr function is allowed to contain a throw as long as constant evaluation never reaches it, so blend(kWarmWhite, kCoolWhite, 50) succeeds and the commented-out blend(..., 150) fails to compile with "not a constant expression". The same guard still works normally at run time, where it throws. One check, enforced at compile time for constants and at run time for everything else — which is a stronger position than either an assert or a comment.
makeRamp shows that a constexpr function may build an aggregate by looping and assigning into it: since C++14 a constant expression can mutate its own locals freely, so long as nothing escapes. The static_asserts on kRamp.front() and kRamp.back() then act as unit tests that run during the build and cost nothing afterwards — if somebody swaps the two endpoint colours, the build breaks with a pointed message instead of the strip lighting up the wrong shade.
packedSize uses if constexpr rather than constexpr alone, and the difference is worth naming. constexpr decides when the value is computed; if constexpr decides which code exists at all. Only the branch matching Channels is instantiated, so the 4-channel marker logic is not compiled into a 3-channel build. A plain if would have compiled all three branches and relied on the optimiser to drop two.
Finally, kMidpoint.scaled(brightness) calls a constexpr member function with a value that does not exist until the program runs, and it works normally — no special case, no duplicate implementation. That symmetry is the practical payoff: mark it constexpr, use it wherever you like, and the compiler takes the compile-time path whenever it can.
Common Mistakes
- Expecting
constexpron a function to force compile-time evaluation. It is a permission. Assign the result to aconstexprvariable, use it in astatic_assert, or mark the functionconsteval. - Confusing
constwithconstexpr.const int n = readInput();is legal and is not a constant expression, so it cannot size an array. - Putting a
std::stringorstd::unique_ptrin a type you want as aconstexprobject. The destructor is not trivial. Usestd::string_viewandstd::array. - Forgetting that a
constexprvariable isconst. Assigning to one will not compile; useconstinitif you want compile-time initialisation with runtime mutation. - Reading a non-
constexprglobal, calling a non-constexprfunction, or using astaticlocal inside aconstexprfunction. All of them silently make it runtime-only. - Building enormous tables. A million-entry
constexprarray is interpreted by the compiler and embedded in the binary — slow builds and a fat executable. - Using
if constexprwhere a plainifwas meant, or the reverse.if constexprdiscards a branch at compile time and needs a compile-time condition. - Assuming
constexprimpliesinlinesemantics everywhere.constexprfunctions are implicitlyinline, but aconstexprvariable at namespace scope in a header needsinline(C++17) to avoid one copy per translation unit.
Best Practices
- Prefer
constexprover#defineand overenumconstants: it is typed, scoped and debuggable. - Mark a function
constexprwhen it is a pure computation over its arguments; it costs nothing and stays usable at run time. - Use
static_assertonconstexprresults as free unit tests that run during the build. - Generate lookup tables with a
constexprfunction instead of pasting numbers into an array by hand. - Reach for
constevalwhen a runtime call would be a bug, andconstinitfor static data you want initialised beforemainbut mutable afterwards. - Keep
constexprtypes literal:std::array,std::string_view, plain arithmetic members. - Use
if constexprfor compile-time branching in templates, and keep it separate in your head fromconstexprevaluation. - Watch build times when tables grow, and measure before assuming compile-time work is always the better trade.
Practice Exercises
- Write
constexpr std::array<std::uint8_t, 256> makeCrc8Table(std::uint8_t polynomial)that builds a CRC-8 lookup table at compile time, plus aconstexpr std::uint8_t crc8(std::string_view data)that uses it. Addstatic_asserts pinning the checksum of two known strings, then deliberately change one table entry and confirm the build fails rather than the program. - Build a
constexprVersiontype withmajor,minorandpatch, aconstexprcomparison, and aconstevalparseVersion(std::string_view)that turns"2.7.1"into aVersionand rejects malformed input by reaching athrow. Prove with a commented-out line thatparseVersion("2..1")is a compile error, and that the same type still compares correctly against a version read at run time. - Measure what compile-time evaluation actually costs. Write a
constexprfunction that builds a table of 4096 sine values and store it two ways: once in aconstexpr autotable, once in a plain array filled by a loop inmain. Time a clean build of each and compare the binary sizes, then add astd::is_constant_evaluated()branch to the generator that uses a cheap polynomial at compile time andstd::sinat run time. Report which version you would ship for a desktop tool and which for a microcontroller, and say what evidence changed your mind.