Lesson 4 of 5
constexpr, if constexpr & Compile-Time Programming
`constexpr` functions and variables are evaluated **at compile time** when called with constant expressions - they generate no runtime code. `if constexpr` (C++17) allows template branches to be discarded at compile time based on type information - the discarded branch isn't even compiled, which is how type-dependent code works without SFINAE. Together, they enable powerful zero-overhead abstractions.
constexpr Functions, Variables & if constexpr Branches
#include <iostream>
#include <array>
#include <type_traits>
#include <string>
// ── constexpr function - evaluated at compile time ──────────
constexpr int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n-1); // recursive constexpr OK
}
constexpr double power(double base, int exp) {
double result = 1.0;
for (int i = 0; i < exp; ++i) result *= base;
return result;
}
// ── constexpr variable - computed at compile time ─────────────
constexpr int LOOKUP[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34}; // fib values
constexpr int N_FACS = factorial(10); // 3628800 - computed at compile time
// ── constexpr class ────────────────────────────────────────────
class Vec3 {
public:
double x, y, z;
constexpr Vec3(double x, double y, double z) : x(x), y(y), z(z) {}
constexpr Vec3 operator+(const Vec3& o) const { return {x+o.x, y+o.y, z+o.z}; }
constexpr double dot(const Vec3& o) const { return x*o.x + y*o.y + z*o.z; }
constexpr double length_sq() const { return dot(*this); }
};
constexpr Vec3 origin{0,0,0};
constexpr Vec3 unit_x{1,0,0};
constexpr Vec3 unit_y{0,1,0};
constexpr double dot_xy = unit_x.dot(unit_y); // 0.0 - compile time
// ── if constexpr - compile-time branch selection ───────────────
template<typename T>
std::string to_string_typed(const T& val) {
if constexpr (std::is_same_v<T, bool>) {
return val ? "true" : "false";
} else if constexpr (std::is_integral_v<T>) {
return std::to_string(val);
} else if constexpr (std::is_floating_point_v<T>) {
return std::to_string(val);
} else if constexpr (std::is_same_v<T, std::string>) {
return '"' + val + '"';
} else {
// This branch compiled only for types that don't match above
// If T lacks operator<<, you'd get error here - not in other branches
return "[unknown type]";
}
}
// ── Template + if constexpr - type trait based dispatch ───────
template<typename Container>
void print_container(const Container& c) {
if constexpr (requires { c.size(); }) {
std::cout << "size=" << c.size() << " ";
}
for (const auto& v : c) std::cout << v << " ";
std::cout << "
";
}
// ── constexpr array - fully computed at compile time ──────────
constexpr std::array<int, 10> make_squares() {
std::array<int, 10> arr{};
for (int i = 0; i < 10; ++i) arr[i] = i * i;
return arr;
}
constexpr auto SQUARES = make_squares(); // [0,1,4,9,16,25,36,...] at compile time
int main() {
// Compile-time evaluation
static_assert(factorial(5) == 120); // compiler verifies
static_assert(SQUARES[7] == 49);
static_assert(dot_xy == 0.0);
// Runtime use of constexpr result
std::cout << "10! = " << N_FACS << "
";
std::cout << "2^10 = " << power(2, 10) << "
";
// if constexpr dispatch
std::cout << to_string_typed(42) << "
"; // 42
std::cout << to_string_typed(true) << "
"; // true
std::cout << to_string_typed(3.14) << "
"; // 3.140000
std::cout << to_string_typed(std::string{"hi"}) << "
"; // "hi"
// Print containers
std::vector<int> v{1,2,3,4,5};
std::array<int,3> a{10,20,30};
print_container(v);
print_container(a);
return 0;
}Common Mistakes
- `constexpr` doesn't guarantee compile-time evaluation - `constexpr int n = factorial(5)` is compile-time. `int n = factorial(5)` (non-const) may or may not be. To force compile-time: use `consteval` (C++20) or assign to a `constexpr` variable.
- `if constexpr` is NOT the same as regular `if` - in regular `if`, both branches must compile for all T. In `if constexpr`, the not-taken branch is not instantiated. This allows `if constexpr (is_same_v<T, std::string>) val.length()` - wouldn't compile for `int` in a regular `if`.
- All branches of `if constexpr` must be syntactically valid - even though only one branch is instantiated for a given T, all branches must parse correctly. `val.nonexistent_method()` in a discarded branch still causes a parse error. Use fully separate templates if needed.
Tip
Tip
Practice constexpr if constexpr CompileTime Programming in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Zero runtime overhead execution during compilation phase
Practice Task
Note
Practice Task - (1) Write a working example of constexpr if constexpr CompileTime Programming from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with constexpr if constexpr CompileTime Programming is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- `constexpr` functions and variables are evaluated **at compile time** when called with constant expressions - they generate no runtime code.
- `constexpr` doesn't guarantee compile-time evaluation - `constexpr int n = factorial(5)` is compile-time. `int n = factorial(5)` (non-const) may or may not be. To force compile-time: use `consteval` (C++20) or assign to a `constexpr` variable.
- `if constexpr` is NOT the same as regular `if` - in regular `if`, both branches must compile for all T. In `if constexpr`, the not-taken branch is not instantiated. This allows `if constexpr (is_same_v<T, std::string>) val.length()` - wouldn't compile for `int` in a regular `if`.
- All branches of `if constexpr` must be syntactically valid - even though only one branch is instantiated for a given T, all branches must parse correctly. `val.nonexistent_method()` in a discarded branch still causes a parse error. Use fully separate templates if needed.
Finished this lesson?