switch and goto
Rocket Run has three difficulty levels, and each sets a different number of enemies. A chain of if (difficulty == ...) tests works, but when you are choosing among fixed values, switch says it more clearly. It has one famous surprise, though.
The rule
switch jumps to the matching case; break stops the fall.
enum class Difficulty { Easy, Normal, Hard };
int enemies = 0;
switch (difficulty) {
case Difficulty::Easy:
enemies = 3;
break;
case Difficulty::Normal:
enemies = 5;
break;
case Difficulty::Hard:
enemies = 8;
break;
}- The value in
switch ( )must be an integer, a character or an enum. Astd::stringordoubleis not allowed. - Each
caselabel must be a constant known at compile time. default:runs when no case matches.- Fall-through: after jumping to a case, execution continues down through the following cases until it hits
break(or the end). When you want that on purpose, mark it with[[fallthrough]];so readers and the compiler know.
goto jumps to a named label in the same function. It still exists, mostly for code that must leave several nested loops in one step:
for (int row = 0; row < 10; ++row)
for (int col = 0; col < 10; ++col)
if (grid[row][col] == ASTEROID) goto found;
std::cout << "No asteroids ahead\n";
found:
std::cout << "Scan finished\n";Most C++ code avoids goto: moving the loops into a function and using return does the same job more readably.
The shortcut
Find the matching case, then run down the page until you meet break. Ignore the other labels on the way; they are only entry points, not walls.
The code
bonusis 0 andkeyis 2. Cases: 1 adds 10, 2 adds 20, 3 adds 30 thenbreak, default adds 1.
Drills
Answer fast — trust the rule.
In the trace above, what would bonus be if key were 1?
Can you write switch (playerName) where playerName is a std::string?
When does the default: branch run?
Which use of goto is the most defensible?
Remember
- switch jumps to the matching case; break stops the fall.
- Shortcut: find the case, then run down until
break. - Trap: a missing
breaksilently runs the next case; use[[fallthrough]]when you mean it.
