The constexpr tells the C++ compiler that a function or a variable can be evaluated at compile time, so the work happens while the program is being built and not when it runs. The result is baked into the binary. For the code that is a table of constants, a lookup table or a fixed set of rules, that turns a run time cost into nothing at all.
The previous lesson in this module covered "What Do Structured Bindings, optional and variant Add?", and this lesson is the last one in the Templates and Modern C++ module.
constexpr functions
A constexpr function may be called with the constant arguments at compile time, and the compiler will evaluate it then.
#include <iostream>
constexpr int measurements_per_hour() {
return 60;
}
constexpr int per_day() {
return measurements_per_hour() * 24;
}
int main() {
std::cout << "per hour: " << measurements_per_hour() << '\n';
std::cout << "per day: " << per_day() << '\n';
static_assert(per_day() == 1440, "a day has 1440 minutes");
return 0;
}The output shows the constants computed before the program started.
per hour: 60
per day: 1440And the static_assert is the real payoff. If the assumption is wrong, then the program does not compile. In C++11 a constexpr function had to be a single return statement, which is why the functions above are written that way.
constexpr variables
A constexpr variable is a constant whose value the compiler knows exactly. It has to be initialised with a constant expression.
#include <iostream>
constexpr int samples = 16;
constexpr double volts = 3.3;
constexpr int table[samples] = {0}; // the size must be a constant expression
int main() {
std::cout << "samples: " << samples << '\n';
std::cout << "volts: " << volts << '\n';
std::cout << "table: " << table[0] << '\n';
return 0;
}The output shows the values.
samples: 16
volts: 3.3
table: 0And because the samples is a constant expression, it can be used as the size of an array. A plain const int would not be allowed for that in C++11.
constexpr and const are not the same
A const variable cannot be modified after the initialisation. A constexpr variable additionally has a value that the compiler can work out at compile time.
#include <iostream>
const int runtime_const = 60; // set at run time
constexpr int compile_time_const = 60; // computed by the compiler
int main() {
std::cout << "runtime const: " << runtime_const << '\n';
std::cout << "compile const: " << compile_time_const << '\n';
// runtime_const cannot be used as an array size in C++11:
// int table[runtime_const];
// But this works, because it is a constant expression:
int table[compile_time_const] = {0};
std::cout << "table size ok: " << (sizeof(table) / sizeof(table[0])) << '\n';
return 0;
}The output shows the difference in what each of them can be used for.
runtime const: 60
compile const: 60
table size ok: 60A lookup table computed at compile time
The classic use of the constexpr is building a table once, at compile time, and reading it at run time.
#include <iostream>
#include <array>
struct Threshold {
int weight;
int label;
};
constexpr std::array<Threshold, 4> build_thresholds() {
return {{{10, 1}, {25, 2}, {50, 3}, {100, 4}}};
}
constexpr std::array<Threshold, 4> thresholds = build_thresholds();
int label_for(int weight) {
int label = 0;
for (const Threshold& threshold : thresholds) {
if (weight >= threshold.weight) {
label = threshold.label;
}
}
return label;
}
int main() {
std::cout << "label for 30: " << label_for(30) << '\n';
std::cout << "label for 120: " << label_for(120) << '\n';
std::cout << "label for 5: " << label_for(5) << '\n';
return 0;
}The output shows the labels coming from the compile-time table.
label for 30: 2
label for 120: 4
label for 5: 0What C++20 changed
C++20 made the constexpr considerably more useful. The loops and the branches in the constexpr functions are allowed from C++14 onwards. The virtual functions may be called in a constant expression. The dynamic_cast and the typeid work at compile time. And the std::vector and the std::string can be used in the constant expressions, but only from C++20.
And a constexpr function does not have to be evaluated at compile time. It merely may be. The practical effect is that more real code can be written as constexpr, which means that more of the bugs are caught at compile time and more of the work is done by the optimiser.
#include <cstddef>
#include <iostream>
constexpr std::size_t length_of(const char* text) {
std::size_t length = 0;
while (text[length] != '\0') {
++length;
}
return length;
}
constexpr int total_length(const char* const* items, std::size_t count) {
int total = 0;
for (std::size_t i = 0; i < count; ++i) {
total += static_cast<int>(length_of(items[i]));
}
return total;
}
int main() {
constexpr const char* items[] = {"p-001", "p-002", "p-003"};
std::cout << "total: " << total_length(items, 3) << '\n';
return 0;
}The output shows the array being traversed at compile time.
total: 15When constexpr is worth it
It is worth it for the tables and the lookup data that are built once and embedded in the binary. It is worth it for the compile-time checks, where a static_assert proves that the configuration is valid. It is worth it for the small computations that are repeated many times at run time. And it is worth it in the template-heavy code where the values are needed to instantiate the types.
And it is not worth it for the ordinary arithmetic. The compiler already optimises the constant arithmetic, and marking a function constexpr restricts what you can write inside it for very little gain.
Quick reference
- The constexpr functions may be evaluated at compile time when they are called with the constant arguments.
- A constexpr variable has a value that the compiler knows, and a const one may not.
- The
static_assertchecks a compile-time condition and it fails the build if it is false. - In C++11 a constexpr function was a single return statement, and C++14 allowed the loops and the branches.
- C++20 allows the virtual calls, the
dynamic_castand the standard containers in the constant expressions. - You use the constexpr for the tables, the compile-time validation and the constants, and not for the ordinary arithmetic.
Try it yourself: write a constexpr function that builds a table of the threshold values and a lookup function that reads it, and then add a static_assert that checks that the table is sorted. Next, change the table so that the assert fails and read the compiler's message. Finally, try using a std::vector inside a constexpr function and see whether your standard library version supports it.