C++
Modelling States With enum class and switch in C++: A Takeaway Kitchen's Order Display
Introduction
A lot of program logic is about things that are always in exactly one of a few states: an order is received, cooking, ready or collected; a traffic light is red, amber or green; a payment is pending, received or refunded. Beginners usually store such a state as an int and remember that 2 means "ready". The compiler cannot remember that for you, so it cannot stop you from passing a table number where a status was expected, or from forgetting a state when you add a new one.
In this tutorial we will build the order display for a takeaway kitchen, the screen above the counter that tells customers whether their order is ready. We will start with integer status codes and watch a swapped argument produce nonsense without a single warning. Then we will replace the integers with a plain enum, find out where it still falls short, move to enum class, and use switch so that the compiler itself tells us which code to update when the kitchen adds a new status.
I will assume you are working in the C/C++ sandbox on Bytestark, in /home/coder/learning, and that you know basic C++: functions, if, loops and std::string. We compile with g++ -std=c++17 -Wall -Wextra.
Background
An enumeration is a type whose possible values are a fixed list of names that you choose. Those names are called enumerators. Under the hood each enumerator is a whole number, counted from 0 unless you say otherwise, but in the code you use the name.
C++ has two kinds of enumeration, and the difference between them is the subject of this tutorial:
- A plain
enum, inherited from C, puts its enumerator names directly into the surrounding scope and lets its values turn intointautomatically. - An
enum class, added in C++11, keeps its names inside the type, so you writeOrderStatus::Ready, and never converts to or fromintunless you ask explicitly.
A scope is the region of code in which a name is visible and refers to one particular thing. Two different things cannot share a name in the same scope.
A switch statement chooses one of several blocks of code by comparing a value against a list of case labels. It is the natural partner of an enumeration, because each case names one enumerator, and the compiler can check whether every enumerator has a case.
Practical Scenario
A busy takeaway kitchen shows every order on a screen above the counter. Each order moves through the same states: the till marks it received, the kitchen starts cooking it, it is put on the pass ready for pickup, and finally the customer collects it. Customers watch the screen for their number, so a wrong status sends someone to the counter for food that does not exist, or leaves food going cold while its owner waits.
The display program was written quickly, with each status stored as an integer and a comment saying what each number means. The till, the kitchen screen and the payment system all pass these numbers around, alongside other integers: order numbers, table numbers, prices.
Now the owner wants a new status: orders can be cancelled, and a cancelled order must say so on the screen. Every piece of code that looks at a status has to learn about it. With integers, nothing tells you where those pieces are.
The Problem
Here is the display code as it is. A comment explains the codes, show_order prints one line for the screen, and main shows order 57, which is ready. The second call to show_order stands for a later edit somewhere else in the program, where someone passed the two arguments the wrong way round.
Create the file:
touch kitchen.cpp
Put this in it:
#include <iostream>
// Status codes: 0 = received, 1 = cooking, 2 = ready, 3 = collected
void show_order(int order_number, int status) {
std::cout << "Order " << order_number << ": ";
if (status == 0) {
std::cout << "received";
} else if (status == 1) {
std::cout << "cooking";
} else if (status == 2) {
std::cout << "READY - please collect";
} else if (status == 3) {
std::cout << "collected";
} else {
std::cout << "unknown status " << status;
}
std::cout << "\n";
}
int main() {
int order_number = 57;
int status = 2;
show_order(order_number, status);
show_order(status, order_number);
return 0;
}
Build it and run it:
g++ -std=c++17 -Wall -Wextra -o kitchen kitchen.cpp && ./kitchen
Order 57: READY - please collect
Order 2: unknown status 57
The first line is right. The second line is what the screen showed after the swapped call: "Order 2", which is someone else's order, with a status of 57. Even with every warning turned on, the compiler said nothing.
It had no reason to. show_order takes two int parameters, and the call passes two int values. That one is an order number and the other is a status exists only in the variable names and in the comment, and the compiler reads neither. Every integer is interchangeable with every other integer.
The if chain has the same weakness from the inside. status == 2 means "ready" only because the comment says so. Someone reading the code has to look up the comment for every number, and someone who writes status == 4 meaning "cancelled" gets no complaint either.
Giving the States Names With enum
The first improvement is to give the states names and a type of their own. Replace the whole of kitchen.cpp with this version, which keeps the swapped call:
#include <iostream>
enum OrderStatus { Received, Cooking, Ready, Collected };
void show_order(int order_number, OrderStatus status) {
std::cout << "Order " << order_number << ": ";
if (status == Received) {
std::cout << "received";
} else if (status == Cooking) {
std::cout << "cooking";
} else if (status == Ready) {
std::cout << "READY - please collect";
} else if (status == Collected) {
std::cout << "collected";
}
std::cout << "\n";
}
int main() {
int order_number = 57;
OrderStatus status = Ready;
show_order(order_number, status);
show_order(status, order_number);
return 0;
}
g++ -std=c++17 -Wall -Wextra -o kitchen kitchen.cpp && ./kitchen
kitchen.cpp: In function ‘int main()’:
kitchen.cpp:23:24: error: invalid conversion from ‘int’ to ‘OrderStatus’ [-fpermissive]
23 | show_order(status, order_number);
| ^~~~~~~~~~~~
| |
| int
kitchen.cpp:5:47: note: initializing argument 2 of ‘void show_order(int, OrderStatus)’
5 | void show_order(int order_number, OrderStatus status) {
| ~~~~~~~~~~~~^~~~~~
The swapped call no longer compiles. Let's see what changed.
enum OrderStatus { Received, Cooking, Ready, Collected }; creates a new type, OrderStatus, whose values are the four names in braces. They are numbered automatically: Received is 0, Cooking 1, Ready 2 and Collected 3, the same codes as before. The comment explaining them is gone because the names explain themselves.
The second parameter of show_order is now OrderStatus, not int, and the comparisons read status == Ready instead of status == 2. In the swapped call, the second argument is order_number, an int, and C++ will not turn an arbitrary int into an OrderStatus on its own: 57 is not one of the four states. The error says exactly that, and the note shows which parameter it was trying to fill.
Delete the line show_order(status, order_number); and run again:
g++ -std=c++17 -Wall -Wextra -o kitchen kitchen.cpp && ./kitchen
Order 57: READY - please collect
This is a real improvement, but a plain enum still has two weak spots. The first is that the conversion only fails in one direction. Add these two lines after the remaining show_order call:
int table = status;
std::cout << "table " << table << "\n";
g++ -std=c++17 -Wall -Wextra -o kitchen kitchen.cpp && ./kitchen
Order 57: READY - please collect
table 2
A status was silently used as a table number. A plain enum value converts to int automatically whenever an int is expected, so int table = status; compiles and copies the number behind Ready, which is 2. Remove those two lines again.
The second weak spot shows up when the program grows. The payment system has its own states, and one of them is also called "received". Add this line right below the OrderStatus line:
enum PaymentStatus { Pending, Received, Refunded };
g++ -std=c++17 -Wall -Wextra -o kitchen kitchen.cpp && ./kitchen
kitchen.cpp:4:31: error: ‘Received’ conflicts with a previous declaration
4 | enum PaymentStatus { Pending, Received, Refunded };
| ^~~~~~~~
kitchen.cpp:3:20: note: previous declaration ‘OrderStatus Received’
3 | enum OrderStatus { Received, Cooking, Ready, Collected };
| ^~~~~~~~
A plain enum puts its enumerator names into the surrounding scope, here the whole file. Received from OrderStatus is just Received, a name visible everywhere, so a second Received is a second thing with the same name in the same scope, which is not allowed. With plain enums, the usual workaround is prefixing every name, as in OrderReceived and PaymentReceived, which is exactly the kind of convention the compiler cannot enforce. Remove the PaymentStatus line.
Try it: Change OrderStatus status = Ready; to OrderStatus status = 2; and rebuild. Predict whether a plain enum accepts the number behind Ready. It does not: you get error: invalid conversion from ‘int’ to ‘OrderStatus’, the same rule that rejected the swapped call. A plain enum converts to int freely but never from it. Put Ready back.
Keeping Names Inside the Type With enum class
enum class fixes both weak spots at once: its names stay inside the type, and it never converts to int on its own. Replace the whole of kitchen.cpp with this version, which also brings back the payment states:
#include <iostream>
enum class OrderStatus { Received, Cooking, Ready, Collected };
enum class PaymentStatus { Pending, Received, Refunded };
void show_order(int order_number, OrderStatus status) {
std::cout << "Order " << order_number << ": ";
if (status == OrderStatus::Received) {
std::cout << "received";
} else if (status == OrderStatus::Cooking) {
std::cout << "cooking";
} else if (status == OrderStatus::Ready) {
std::cout << "READY - please collect";
} else if (status == OrderStatus::Collected) {
std::cout << "collected";
}
std::cout << "\n";
}
int main() {
int order_number = 57;
OrderStatus status = OrderStatus::Ready;
PaymentStatus payment = PaymentStatus::Received;
show_order(order_number, status);
if (payment == PaymentStatus::Received) {
std::cout << "Order " << order_number << ": paid\n";
}
return 0;
}
g++ -std=c++17 -Wall -Wextra -o kitchen kitchen.cpp && ./kitchen
Order 57: READY - please collect
Order 57: paid
Both enumerations now have a Received, and the program compiles. The only difference in the declarations is the word class after enum, but it changes how every name is used.
With enum class, the enumerators belong to the type's own scope, not to the file. Outside the type, you reach them through the type name and the scope resolution operator ::, the same operator as in std::cout. So OrderStatus::Received and PaymentStatus::Received are two different names, as different as std::cout and some other cout would be. That is why every comparison in show_order now reads status == OrderStatus::Ready. It is longer to type, and it says at every use which kind of status is meant.
The other change does not show in the output, because it is about code that no longer compiles. An enum class value does not turn into an int by itself, and two different enum class types cannot be compared with each other. A line like if (payment == OrderStatus::Received), which mixes up the order and the payment, is rejected with no match for ‘operator==’ (operand types are ‘PaymentStatus’ and ‘OrderStatus’). With plain enums, such a comparison compiles: both values are converted to int and compared as numbers, so a payment that is Pending (0) compares equal to an order that is Received (0), and g++ only warns comparison between ‘enum PaymentStatus’ and ‘enum OrderStatus’.
When you really do need the number, for example to store a status in a database column, you ask for it explicitly with static_cast<int>(status), which gives 2 for OrderStatus::Ready. The conversion is still possible; it just cannot happen by accident.
Try it: Add the line int table = status; after the show_order call and rebuild. Predict the result, given that the same line compiled with a plain enum. It is now error: cannot convert ‘OrderStatus’ to ‘int’ in initialization. Then replace it with std::cout << "stored as " << static_cast<int>(status) << "\n"; and run: the screen prints stored as 2 between the two other lines, because the explicit cast is allowed. Remove the line again.
Choosing by State With switch
The display needs two pieces of logic for each status: the text to show, and the status an order moves to next when the kitchen presses its button. A long if/else if chain works, but C++ has a statement built for exactly this. Replace the whole of kitchen.cpp with:
#include <iostream>
#include <string>
enum class OrderStatus { Received, Cooking, Ready, Collected };
std::string label(OrderStatus status) {
switch (status) {
case OrderStatus::Received:
return "received";
case OrderStatus::Cooking:
return "cooking";
case OrderStatus::Ready:
return "READY - please collect";
case OrderStatus::Collected:
return "collected";
}
return "unknown";
}
OrderStatus next_status(OrderStatus status) {
switch (status) {
case OrderStatus::Received:
return OrderStatus::Cooking;
case OrderStatus::Cooking:
return OrderStatus::Ready;
case OrderStatus::Ready:
case OrderStatus::Collected:
return OrderStatus::Collected;
}
return status;
}
int main() {
int order_number = 57;
OrderStatus status = OrderStatus::Received;
while (true) {
std::cout << "Order " << order_number << ": " << label(status) << "\n";
if (status == OrderStatus::Collected) {
break;
}
status = next_status(status);
}
return 0;
}
g++ -std=c++17 -Wall -Wextra -o kitchen kitchen.cpp && ./kitchen
Order 57: received
Order 57: cooking
Order 57: READY - please collect
Order 57: collected
Order 57 is walked through its whole life, one screen line per state. The payment states are gone from this version to keep the focus on orders; they would live in the program exactly as before.
Let's start with label. switch (status) evaluates status once and jumps straight to the case label whose value matches. Each case here ends with return, which leaves the whole function with the text for that state. So for OrderStatus::Ready, execution jumps to that label and returns "READY - please collect".
The return "unknown"; after the switch may look pointless, since every enumerator has a case. It is there because an enum class variable can, in rare cases, hold a value that is not one of its enumerators, for instance if someone writes static_cast<OrderStatus>(7). For such a value no case matches, execution continues after the switch, and the function must still return something. If you delete that line, g++ warns control reaches end of non-void function [-Wreturn-type], pointing at the closing brace of label.
next_status describes how an order moves through the kitchen. Received becomes cooking, cooking becomes ready. Look at the last part:
case OrderStatus::Ready:
case OrderStatus::Collected:
return OrderStatus::Collected;
Two labels stand in front of one return. A case label is only a place to jump to, not a separate block, so execution that lands on case OrderStatus::Ready: simply continues to the next line, passes the second label, and reaches the return. Both states therefore move to Collected: a ready order is collected next, and a collected order stays collected. Stacking labels like this is how you give several values the same handling.
This "continue to the next line" behaviour is also the classic switch trap. If a case does something other than return, for example prints a line, it must end with break;, which jumps out of the switch. Without it, execution falls into the next case's code as well. Since every case here returns, we never need break.
In main, the while (true) loop prints the current state, stops once the order is collected, and otherwise moves it on with next_status. Notice that main contains no list of states and no numbers: everything it knows about statuses comes from the two functions.
Try it: In next_status, delete the line case OrderStatus::Ready: and rebuild. Predict two things: does the compiler notice, and what does the screen do? g++ warns enumeration value ‘Ready’ not handled in switch, and the program prints Order 57: READY - please collect over and over until you press Ctrl+C. With no case for Ready, execution falls out of the switch to return status;, the order stays ready forever, and the loop never reaches Collected. Put the line back.
Adding a New Status: Letting the Compiler Find Every Switch
Now for the owner's request: orders can be cancelled. Start with the change everyone makes first. Add Cancelled to the end of the enumeration:
enum class OrderStatus { Received, Cooking, Ready, Collected, Cancelled };
And add a cancelled order, number 58, at the end of main, just before return 0;:
OrderStatus order_58 = OrderStatus::Cancelled;
std::cout << "Order 58: " << label(order_58) << "\n";
g++ -std=c++17 -Wall -Wextra -o kitchen kitchen.cpp && ./kitchen
kitchen.cpp: In function ‘std::string label(OrderStatus)’:
kitchen.cpp:7:12: warning: enumeration value ‘Cancelled’ not handled in switch [-Wswitch]
7 | switch (status) {
| ^
kitchen.cpp: In function ‘OrderStatus next_status(OrderStatus)’:
kitchen.cpp:21:12: warning: enumeration value ‘Cancelled’ not handled in switch [-Wswitch]
21 | switch (status) {
| ^
Order 57: received
Order 57: cooking
Order 57: READY - please collect
Order 57: collected
Order 58: unknown
This is the payoff of the whole tutorial. The compiler lists every switch on OrderStatus that has no case for the new state: one in label at line 7, one in next_status at line 21. In a real program those could be in twenty files; the warning finds them all. The flag in brackets, -Wswitch, is one of the warnings -Wall turns on. It works because the compiler knows the complete list of enumerators, which it could never know for a plain int.
The program still built, because these are warnings, and the last line shows what ignoring them costs: order 58 appears on the screen as unknown, because no case matched in label and the fallback text was returned.
Handle the new state in both functions. In label, add a case after Collected:
case OrderStatus::Cancelled:
return "CANCELLED - see the counter";
In next_status, add a case after the Ready/Collected pair, so that a cancelled order stays cancelled:
case OrderStatus::Cancelled:
return OrderStatus::Cancelled;
g++ -std=c++17 -Wall -Wextra -o kitchen kitchen.cpp && ./kitchen
Order 57: received
Order 57: cooking
Order 57: READY - please collect
Order 57: collected
Order 58: CANCELLED - see the counter
The build is clean, and order 58 shows the right message. Both functions now have a case for every enumerator, so -Wswitch has nothing to report. Cancelled is a final state like collected: once there, next_status keeps it there.
This is also why neither switch has a default: label, the catch-all that runs when no case matches. With a default, a switch counts as handling every value, so the compiler has nothing to warn about when a new enumerator is added.
Try it: In label, replace the two Cancelled lines with default: return "unknown"; and rebuild. Predict whether you get a warning and what order 58 shows. The build is silent and the screen says Order 58: unknown, exactly the bug the warning caught a moment ago, now hidden. Put the Cancelled case back and remove the default.
Summary
We turned an order display built on integer codes into one where each status has a name and a type, where mixing a status with an order number or with a payment status does not compile, and where adding a new status makes the compiler point at every switch that needs updating. We kept the transitions simple, one fixed path per order. Rules such as "only received or cooking orders can be cancelled" belong in next_status-style functions and would make a good exercise.
- Storing states as
intcodes lets any integer stand in for a state, so swapped arguments and invalid codes compile without complaint. - A plain
enumgives states names and rejects anintwhere the enum is expected, but converts tointsilently and puts its names into the surrounding scope, where they can clash. enum classkeeps its enumerators inside the type, used asOrderStatus::Ready, and never converts tointor to another enum by itself; ask for the number explicitly withstatic_cast<int>.switchjumps to the matchingcaselabel. Acasethat does notreturnneedsbreak, or execution continues into the next case.- Stacking several
caselabels in front of one block gives those values the same handling. - Keep a
returnafter aswitchthat returns from everycase, because an enum variable can still hold an unlisted value. - With
-Wall,-Wswitchwarns about everyswitchon an enum that misses an enumerator, which turns adding a new state into a checklist the compiler writes for you. - Leave out
default:in aswitchover an enum, since adefaultsilences exactly that warning.