Modern C++ • C++20 baseline
const, constexpr, and Compile-Time Values
Distinguish read-only objects from expressions that must be evaluated at compile time.
const prevents modification through a particular name after initialization. constexpr additionally requires a value or function result to be usable in constant evaluation when its inputs permit that. Do not mark everything constexpr by habit: first state the requirement, then choose the narrowest facility that satisfies it.
Key points
- A const object can be initialized at runtime.
- constexpr functions can also run at runtime with non-constant inputs.
Example
#include <array>
#include <iostream>
constexpr int square(int value) {
return value * value;
}
int main() {
constexpr int grid_size = square(4);
const std::array<int, grid_size> cells{};
std::cout << cells.size() << '\n';
}
What to expect
16
Practice exercise
Write a constexpr function that converts minutes to seconds and use it to size a std::array.
Key idea: Use constexpr when compile-time evaluation is a useful requirement, not just as decoration.