Lesson contents

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

  1. Start with Unit is 3
  2. Do this Multiply by 2
  3. Result 6
Give 3 a name and reuse that name in the multiplication.
lesson.cpp
#include <iostream>

int main() {
    constexpr int unit = 3;
    std::cout << 2 * unit << '\n';
}
Output
6
Advertisements

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.

Length of a slot: 30 minutes. Rehearsal: 3 slots. Time reserved: 90 minutes.
Reserve a rehearsal room

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
lesson.cpp
#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;
}
Output
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.

C++17 working draft

Related tags

  • C++
  • constants
  • bindings
  • configuration