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
- Start with Value 2
- Do this Match case 2
- Result two
#include <iostream>
int main() {
int n = 2;
switch (n) {
case 2: std::cout << "two\n"; break;
default: std::cout << "other\n";
}
}
two
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.
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
#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;
}
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.