switch and goto
A switch jumps to the case label matching an integer or enum value and runs on until a break, while goto jumps to a label and is kept for rare cases.
Compare multi-way selection with explicit jumps, paying attention to fall-through.
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.