C++ Intermediate · Lesson 15 of 27
constexpr (C++17)
Computing values at compile time, constexpr functions and constexpr if.
Estimated time · 45–60 min
Learning goals
What you will understand
- Explain constexpr (c++17) in your own words
- Use it in a small robotics example
- Verify the result instead of assuming it worked
Understand the idea first
The mental model
constexpr tells the compiler a value or function can be evaluated at compile time. Compile-time results cost nothing at run time and can be used in places that need constants, such as std::array sizes and static_assert. In C++17 constexpr functions can contain loops and conditions.
Use constexpr for constants (limits, conversion factors) and small pure functions. A constexpr function called with run-time arguments still works normally; it is only evaluated at compile time when all arguments are constants.
Guided lesson
Work through these steps
- 1.
Read the constexpr (c++17) example and identify what each line owns or changes.
- 2.
Create a small source file, compile with -std=c++17 and warnings enabled, and run it.
- 3.
Change one input, predict the result before running, then compare the output.
- 4.
Record one compiler or runtime error and explain the correction in your own words.
Worked example
Read it before you run it
constexpr double pi = 3.14159265358979;
// A compile-time constant.
constexpr double deg_to_rad(double deg) {
// A function the compiler can run while compiling.
return deg * pi / 180.0;
// Simple arithmetic is allowed.
}
// End of deg_to_rad.
constexpr double quarter_turn = deg_to_rad(90.0);
// Evaluated at compile time; no run-time cost.
static_assert(quarter_turn > 1.57 && quarter_turn < 1.58, "unit conversion is wrong");
// Compile-time proof the conversion works.
constexpr int factorial(int n) {
// C++17 allows loops in constexpr functions.
int r = 1; for (int i = 2; i <= n; ++i) r *= i; return r;
// Multiply 2..n.
}
// End of factorial.
std::array<double, factorial(4)> table{};
// The array size (24) is computed at compile time.What the example is doing
- 1.Read declarations from right to left: identify each value's type, name, and initial value.
- 2.Follow the data through each expression before considering syntax shortcuts.
- 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.
Watch it run · Values in memory
See what this code does
The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.
Demo for constexpr (C++17). Expected result: 24
Practice code
Now type it yourself
Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice
#include <array>
#include <iostream>
// TODO: write constexpr factorial(int n) with a loop
static_assert(factorial(4) == 24, "factorial is wrong");
int main() {
std::array<double, factorial(4)> table{}; // size computed at compile time
std::cout << table.size() << '\n';
return 0;
}Expected output
24Stuck? Show the full solution (try it yourself first)
#include <array>
#include <iostream>
constexpr int factorial(int n) {
int r = 1;
for (int i = 2; i <= n; ++i) r *= i;
return r;
}
static_assert(factorial(4) == 24, "factorial is wrong");
int main() {
std::array<double, factorial(4)> table{}; // size computed at compile time
std::cout << table.size() << '\n';
return 0;
}Expected result
How you know it worked
- After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
- Changing the stated input produces the result you predicted.
Practical exercise
Apply the lesson
Write a constexpr function that converts encoder ticks to degrees. Use it to size a lookup table and add a static_assert for two known values. Call it once with a runtime value too.
Before you continue
- The program builds with -std=c++17 and no warnings
- You can explain the key rule without reading the example
- The normal and edge cases both have recorded results
If something goes wrong
Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.
Print the inputs and intermediate values, then check conversions, units, and collection order.