The switch statement and the enum type model choices in C++ by giving a fixed set of possibilities a name and a type. A switch dispatches on the value of one expression, and an enum enumerates the legal values so that the compiler can check that you used a real one. Together they replace a long else if ladder with something the reader can scan in one pass.
The previous lesson in this module covered "How Do if and else Chain Decisions Together?", and the next lesson in this module is about "How Do the Three Loops Differ in C++?".
Defining the choices with an enum
An enumeration names a set of integer constants. The underlying type is an integer, but the named values are what your code actually uses.
#include <iostream>
enum PizzaSize {
Small,
Medium,
Large,
Party
};
int main() {
PizzaSize chosen = Medium;
std::cout << "chosen size value: " << chosen << "\n";
std::cout << "large value: " << Large << "\n";
return 0;
}Without an explicit initialiser the values count up from zero, so Small is 0, Medium is 1 and so on. You can set them yourself when the numbers matter.
#include <iostream>
enum PizzaSize {
Small = 10,
Medium = 12,
Large = 16,
Party = 22
};
int main() {
std::cout << "diameter: " << Medium << " inches\n";
return 0;
}Scoped enums keep names out of the way
An unscoped enum leaks its names into the enclosing scope, so Small might collide with something else. A scoped enum, written enum class, nests the names inside the type, and it requires the type name when you use them.
#include <iostream>
enum class PizzaSize {
Small,
Medium,
Large,
Party
};
enum class Topping {
ExtraCheese,
Olives,
Basil
};
int main() {
PizzaSize chosen = PizzaSize::Large;
Topping extra = Topping::Basil;
std::cout << "size value: " << static_cast<int>(chosen) << "\n";
std::cout << "topping value:" << static_cast<int>(extra) << "\n";
return 0;
}Scoped enums also do not convert to integers implicitly, and that is exactly why the static_cast is needed. That extra step is a feature, because it stops a size from being passed where a topping is expected.
Dispatching with switch
A switch evaluates one expression and jumps to the matching case. Each case ends with a break, and the break is what stops the fall-through.
#include <iostream>
enum class PizzaSize { Small, Medium, Large, Party };
int main() {
PizzaSize size = PizzaSize::Large;
int price = 0;
switch (size) {
case PizzaSize::Small:
price = 899;
break;
case PizzaSize::Medium:
price = 1299;
break;
case PizzaSize::Large:
price = 1699;
break;
case PizzaSize::Party:
price = 2299;
break;
}
std::cout << "price: " << price << "\n";
return 0;
}The switch reads like a table. There is one expression at the top, one label per row, and the body of each case is the code that belongs to that row.
Fall-through is a bug until it is a feature
If you forget the break, then the execution continues into the next case and runs its body as well. That is called fall-through.
#include <iostream>
int main() {
int extra_toppings = 1;
int charge = 0;
switch (extra_toppings) {
case 0:
charge = 0;
break;
case 1:
charge = 100; // no break: falls into case 2
// fall through
case 2:
charge += 50;
break;
default:
charge += 25;
break;
}
std::cout << "charge: " << charge << "\n";
return 0;
}One topping costs 150 rather than 100, because the single-topping case added 100 and then fell through and added another 50. Most of the time an accidental fall-through is a bug, and the compiler will warn about it when you compile with -Wall.
Fall-through is occasionally deliberate, when you are grouping the cases that share a body. C++17 has an attribute that says so on purpose.
#include <iostream>
int main() {
int extra_toppings = 3;
int charge = 0;
switch (extra_toppings) {
case 3:
charge += 25;
[[fallthrough]];
case 2:
charge += 50;
break;
default:
break;
}
std::cout << "charge: " << charge << '\n';
return 0;
}The [[fallthrough]]; attribute tells the compiler that the fall-through is on purpose, so it does not warn. GCC and Clang also accept a plain comment such as "// fall through" as a signal of intent.
The default case and matching a range
The default label runs when nothing else matched. Always include it, even if it only prints a message, because it documents that you thought about the other cases.
A switch can also match a range of values by using the case-with-initializer syntax that was added in C++17.
#include <iostream>
int main() {
int delivery_minutes = 42;
const char* status = "unknown";
switch (delivery_minutes) {
case 0:
status = "not started";
break;
default:
if (delivery_minutes < 30) {
status = "on the way";
} else if (delivery_minutes <= 60) {
status = "arriving soon";
} else {
status = "delayed";
}
break;
}
std::cout << "status: " << status << "\n";
return 0;
}A switch only works on integral and enumeration types, and the case labels have to be constant expressions. If your choices are not a fixed set of values, then use an if ladder instead.
When to use switch and when to use if
Use a switch when the expression is a small fixed set of named values, such as a status, a menu choice or a state machine. Use if chains when the conditions involve ranges, floating point comparisons or compound logic.
The practical test is whether a reader can scan your switch and see every option. If the list is long and each case needs different logic, then an if ladder may read better. If the values are named and discrete, then the switch wins, because it makes the exhaustiveness visible.
Quick reference
- An enum names a set of integer constants, and a scoped
enum classkeeps the names inside the type. - Scoped enums do not convert to integers implicitly, so use
static_cast<int>. - A switch matches one expression against the case labels.
- Every case needs a break, or it falls into the next one.
- Mark an intentional fall-through with
[[fallthrough]];in C++17. - Always write a default case, even a trivial one.
- A switch works only on integral and enumeration types with constant case labels.
Try it yourself: define a scoped enum for the pizza size and another for the crust type, and then write a switch that computes a price from both of them. Add a default case for an unknown crust, and compile with -Wall so that you can see the compiler flag a missing break. Then convert the crust switch into an if ladder and decide which version you would rather maintain.