constexpr marks a variable or function as eligible for compile-time evaluation when constant-expression rules allow it. A constexpr variable is const; a constexpr function may still run at runtime when its arguments are not known until then. section 3.3.2
Use constexpr to move suitable checks and calculations earlier in development:
- Combine a constexpr function with static_assert to make the compiler reject a false property, such as is_prime(4). section 3.3.2
- Mark pure calculations such as triangle-number generation so their results can be checked or computed at compile time. section 9.1
- Use constexpr parsing functions with std::optional to validate slot-machine input in static_assert tests. section 9.3.4
Compile-time checks and testable calculations
A constexpr is_prime function can be called normally, while static_assert(is_prime(2)) checks it during compilation and produces a compiler error for a non-prime value. The same pattern supports constexpr make_triangle_numbers, which builds a vector with std::iota and std::partial_sum. In a slot-machine example, a constexpr make_reels function accepts a shuffle operation: runtime code supplies a seeded generator, while a no-op lambda enables a compile-time size check. section 3.3.2 section 9.1 section 9.2.1
Listing 9.1 Making the first few triangle numbers
#include <numeric>
#include <vector>
constexpr std::vector<int> make_triangle_numbers(int count)
{
std::vector<int> numbers(count); #1
std::iota(numbers.begin(), numbers.end(), 1); #2
std::partial_sum(numbers.begin(), numbers.end(), numbers.begin()); #3
return numbers;
}
Shows a complete constexpr function that constructs triangle numbers with standard numeric algorithms. section 9.1


