In high-performance C++ systems (game engines, low-latency financial systems), the microsecond overhead of invoking a small function repeatedly can degrade throughput. C++ provides three powerful tools to optimize or completely pre-compute results at compile time: inline, constexpr, and consteval.
inline Keywordinline int maximum(int a, int b) {
return (a > b) ? a : b;
}
constexpr (C++11)#include <iostream>
// Evaluated at compile time if argument is a constant expression!
constexpr unsigned long long factorial(int n) {
return (n <= 1) ? 1 : (n * factorial(n - 1));
}
int main() {
// Computed entirely by the compiler during compilation!
constexpr auto fact5 = factorial(5); // 120 (hardcoded binary constant)
std::cout << "5! = " << fact5 << std::endl;
return 0;
}
consteval (C++20)consteval int square(int x) {
return x * x;
}
int main() {
constexpr int val = square(10); // OK: Evaluated at compile time (100)
// int runtimeInput = 10;
// int err = square(runtimeInput); // COMPILE ERROR! consteval forbids runtime calls!
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Standard function declarations and calls.
Overloading functions for multiple types.
Overview of C++11 to C++23 features.