C++ switch
The if and else page ended with twenty-nine lines on the screen, and the last one was pass, the value that the if block stored in result. This page starts from that screen, in the same file types.cpp, and the first box still holds the word pine. The new work adds a day box and a name box, and then a switch that chooses one name from the value of day. The screen grows to thirty lines, and the last one is the chosen name.
This page continues the Control Flow module. An if with an else chooses between two paths. A switch chooses among many paths when all of them depend on one value. Think of a menu on a phone, where the number the user presses picks one screen out of several. Writing that choice with a long chain of if and else lines works, but the code becomes hard to read when the chain gets long. A switch puts the value once at the top and lists each possible answer under it.
The file keeps its name, and the same rules apply. The new box day holds the int 3. The string box name starts empty and receives one of several words, and the last line prints it. Nothing else in the file changes, so every line above the switch is the same as on the if and else page.
A switch statement starts with the keyword switch and a value in parentheses. The line switch (day) { reads the value of day once. Under it, each case label names one value that can match, such as case 1:, case 2:, and case 3:. A label is followed by a colon and the statements for that case. The braces after the switch line group all of the cases, and the closing brace ends the statement. When day holds 3, the program jumps to the label case 3: and starts running from there.
The labels must be constant values that the compiler knows when it builds the file. Whole numbers such as 1, 2, and 3 are the common case, and a character such as 'a' also works. A string such as "wed" cannot be used as a label, and neither can a double such as 3.5. The value in parentheses must be an integer type or an enum, and the labels must be of a matching type. For a comparison with a range, such as "between 10 and 20", an if is the right tool, because a switch label names one exact value at a time.
A default: label is optional, and it takes the path when no other label matches. It works like an else for the switch. In this file, day holds 3, so case 3: matches and default: is skipped. If day held 9, no case would match, and the program would run the default: block and set name to other. A switch with a default always has an answer, so the reader does not have to wonder what happens for an unexpected value.
Each case in this file ends with the line break;. The word break ends the switch, so the program leaves the statement and continues with the line after the closing brace. Without it, the program keeps running into the next case, even though that case does not match. Because name is assigned in every case, forgetting a break in this file would store the wrong word in name, and the screen would show a value that does not match the day.
The rule is that a matching case runs until it reaches a break, and then the switch is finished. A missing break is one of the most common bugs in C++ code that uses switch, and many compilers warn about it. Writing the break on every case, including the last case before default, makes each case independent. When you add a new case later, you can copy one block, change the label and the value, and keep the break at the end, without thinking about the cases around it.
The default case also ends with break in this file. It is the last label, so the break is not needed for the logic, but keeping it means that adding another case below default later does not change the meaning of the code. Keeping the same shape for every case is a habit that makes switch statements easy to read.
Type the file in this order, or add only the new lines if types.cpp is already on disk. Under the line std::string result;, add two boxes: int day = 3; and std::string name;. At the end of the file, after the block with wet, add the switch statement with its cases and the default, then one print line for name. The file name on disk stays types.cpp. The checked file is below, and the new lines are the two boxes, the switch with its cases, and the print line before return 0;.
#include <iostream>
#include <string>
int main()
{
// the word stays pine
std::string word = "pine";
int count = 2;
double ratio = 0.5;
bool ready = true;
double price = 7.9;
const int limit = 10;
int scores[3] = {4, 5, 6};
std::string other = "cone";
std::string joined = word + " " + other;
int total = 17;
int step = 3;
step += 4;
int score = 72;
int goal = 50;
bool wet = false;
std::string result;
int day = 3;
std::string name;
std::cout << word << std::endl;
std::cout << count << std::endl;
std::cout << ratio << std::endl;
std::cout << ready << std::endl;
std::cout << word.size() << std::endl;
std::cout << joined << std::endl;
std::cout << word[0] << std::endl;
std::cout << joined.find("cone") << std::endl;
std::cout << joined.substr(5, 4) << std::endl;
std::cout << count * 4 << std::endl;
std::cout << 7 / 2 << std::endl;
std::cout << 7.0 / 2 << std::endl;
std::cout << (count > 1) << std::endl;
std::cout << (count == 3) << std::endl;
std::cout << !ready << std::endl;
std::cout << static_cast<int>(price) << std::endl;
std::cout << static_cast<double>(count) / 4 << std::endl;
std::cout << static_cast<int>(ratio * 3) << std::endl;
std::cout << limit << std::endl;
std::cout << limit * count << std::endl;
std::cout << scores[0] << std::endl;
std::cout << scores[2] << std::endl;
std::cout << total % 5 << std::endl;
std::cout << step << std::endl;
std::cout << (score >= goal) << std::endl;
std::cout << (score < goal) << std::endl;
std::cout << ((score >= goal) && (count == 2)) << std::endl;
std::cout << ((score < goal) || wet) << std::endl;
if (score >= goal) {
result = "pass";
} else {
result = "retry";
}
std::cout << result << std::endl;
if (wet) {
std::cout << "wet" << std::endl;
}
switch (day) {
case 1:
name = "mon";
break;
case 2:
name = "tue";
break;
case 3:
name = "wed";
break;
default:
name = "other";
break;
}
std::cout << name << std::endl;
return 0;
}
Rebuild with g++ -std=c++17 types.cpp -o types, then run ./types. If g++ is missing and clang++ is the compiler you installed, swap only the tool name: clang++ -std=c++17 types.cpp -o types. The screen shows thirty lines. The first twenty-nine are the same as on the if and else page. The thirtieth line is name, which prints the word wed.
Check the thirtieth line first. The value of day is 3, so the switch jumped to case 3:, set name to wed, and reached its break. The default: block was skipped. The screen shows wed, and the table gives each row its piece, so compare your run with it line by line. If the screen shows other on the last line, check that day holds 3 and that the case for 3 ends with break.
📊 The switch and what it shows
| Piece | What the screen shows |
|---|---|
| First | wed, because day is 3, so case 3 runs |
| Last | nothing extra, because the default block is skipped after the break |
| Rule | a switch runs the matching case until break, and default runs only when no case matches |
| Screen | pine, 2, 0.5, 1, 4, pine cone, p, 5, cone, 8, 3, 3.5, 1, 0, 0, 7, 0.5, 1, 10, 20, 4, 6, 2, 7, 1, 0, 1, 0, pass, wed |
Try one change at a time. Change int day = 3; to int day = 5;, and the thirtieth line becomes other, because no case matches 5 and the default block runs. Put the 3 back. Next, delete the break; line that ends case 3: and rebuild. The thirtieth line becomes other again, because the program runs from case 3: into the default block, and default overwrites name. Put the break back. Each experiment changes one thing, so the screen shows exactly which line caused the difference. Undo each change before the next one starts, so the file always returns to the checked version.
This page ends the choice tools for now and stops before the loops. The next page is for, which repeats a block of code a set number of times. The switch you have just written chooses one path, and a loop will run the same path again and again. You leave with thirty lines on the screen, and the last one is wed. Count the lines before you leave. There are thirty, and the last one is wed.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top