C++ — Const and constexpr
constexpr declares a variable whose initialization satisfies constant-expression requirements. const makes an object read-only through that declaration and can also hold a runtime result.
A simple example
Use a fixed value
- Start with Unit is 3
- Do this Multiply by 2
- Result 6
#include <iostream>
int main() {
constexpr int unit = 3;
std::cout << 2 * unit << '\n';
}
6
Name a fixed scheduling interval
Express a 30-minute slot in terms of a 15-minute base interval. Keep the slot count separate so different bookings can reuse the same rule. Both scheduling constants can be used in static_assert. A booking's slot count could instead be read from input and stored in a const local after validation.
The music room can be booked in 30-minute slots. A rehearsal needs three slots, so the calendar sets aside 90 minutes. Naming the slot length lets every booking use the same rule.
Run the example
Use a C++17 compiler. Run these commands from the directory containing the example. Use a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson
#include <iostream>
int main() {
constexpr int base_minutes = 15;
constexpr int slot_minutes = 2 * base_minutes;
static_assert(slot_minutes > 0);
const int booked_slots = 3;
std::cout << booked_slots * slot_minutes << " minutes\n";
return 0;
}
90 minutes
Two base intervals make each slot 30 minutes. A booking of three slots lasts 90 minutes.
Try it yourself
If the base interval changes to 10 minutes, how long is the same three-slot booking?
Check your answer
Each slot now lasts 20 minutes, so the booking lasts 60 minutes.