Lesson contents

C++ — Switch statements with enum class

A switch can dispatch on a scoped enumeration. Several case labels can lead to the same result without duplicating the action.

A simple example

Match one case

  1. Start with Value 2
  2. Do this Match case 2
  3. Result two
The matching case supplies the word. A different value can take the default path.
lesson.cpp
#include <iostream>

int main() {
    int n = 2;
    switch (n) {
        case 2: std::cout << "two\n"; break;
        default: std::cout << "other\n";
    }
}
Output
two
Advertisements

Route several event states to one action

Map queued and retry to the same pending action. A sent event is complete, and an unrecognized state is sent for review. Returning from the function ends each branch immediately. A default action handles a value outside the known business states.

Queued or retry: Pending. Sent: Done. Other status: Review.
Route a parcel update

A parcel dashboard receives status updates. A queued parcel and a parcel awaiting retry both belong in the pending tray. Mark a sent parcel done and send unfamiliar statuses for review.

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>

enum class Event { queued, retry, sent, unknown };
const char *route(Event event) {
    switch (event) {
        case Event::queued:
        case Event::retry: return "pending";
        case Event::sent: return "done";
        default: return "review";
    }
}

int main() {
    for (auto event : {Event::queued, Event::retry, Event::sent, Event::unknown}) {
        std::cout << route(event) << '\n';
    }
    return 0;
}
Output
pending
pending
done
review

Both pending states share one result. The other branches distinguish a known completion from a new or misspelled status.

Try it yourself

What should an unrecognized state such as paused produce?

Check your answer

It produces review. Add an explicit case when the application defines how to handle that state.

C++17 working draft

Related tags

  • C++
  • multiway selection
  • pattern matching
  • default case