๐ C++ Programming Lesson 8: The Switch Statement – A Branching Tool Focused on “Value Matching”

๐ Course Navigation
1ใ๐ค What is the switch statement? (When is it more appropriate to use switch?)2ใ๐ Syntax and Core Elements of the Switch Statement (The roles of case, break, and default)3ใ๐ Programming Case Studies (From basic to practical value matching scenarios)4ใโ ๏ธ Common Mistakes and Pitfall Avoidance Techniques (Avoiding switch logic confusion)5ใ๐ข Next Lesson Preview: For Loop (The “Looping Tool” that allows the program to repeatedly execute code)
1. ๐ค What is the switch statement? – When is it more appropriate to use switch?
In the last lesson, we learned how to use if-else if-else to handle “multiple choices”, but if we need to determine whether a **”variable equals a fixed value”** (such as “day of the week”, “month”, or “menu option number”), using if-else if-else can be redundant.
For example, to determine the day of the week:
// Using if-else if-else to determine the day requires multiple checks for "day == 1" and "day == 2"int day = 3;if (day == 1) { cout << "Monday"; }else if (day == 2) { cout << "Tuesday"; }else if (day == 3) { cout << "Wednesday"; }// ... and we still need to write checks for Thursday to Sunday, making the code repetitive and cumbersome
At this point, the switch statement comes into play! It is specifically designed for “value matching” scenarios, and its core logic is: to compare a variable against multiple fixed values one by one, and upon finding a match, execute the corresponding code, resulting in a more concise and readable code structure.
๐ Scenarios in life suitable for using switch:
- ๐ Determining the day of the week (1 = Monday, 2 = Tuesdayโฆ 7 = Sunday);
- ๐ Determining the month (1 = January, 2 = Februaryโฆ 12 = December);
- ๐ Menu selection (1 = Query, 2 = Modify, 3 = Exit);
- ๐ฎ Game character selection (1 = Warrior, 2 = Mage, 3 = Archer).
2. ๐ Syntax and Core Elements of the Switch Statement
(1) Basic Syntax Format
The switch statement is like a “value matching reference table”, structured as follows:
switch (variable) { // The variable must be of integer type (int, char, etc., cannot be double/float) case value1: // When "variable == value1", execute the following code // Code block 1 break; // Exit the switch statement to avoid executing subsequent cases (critical!) case value2: // When "variable == value2", execute the following code // Code block 2 break; // ... (more cases can be added for different values) default: // When the variable does not match any case values, execute this code (optional) // Fallback code block break; // It is also recommended to add break after default for consistency}
(2) Core Element Analysis
๐ 1. switch(variable):
- The “variable” in parentheses must beof integer type (int, char, short, etc.), and cannot be a floating-point number (double/float) or a string! This is because floating-point numbers have precision errors and cannot match values accurately.
- For example, switch(day) (where day is of int type) and switch(choice) (where choice is of int type) are valid, but switch(price) (where price is of double type) will cause an error!
๐ 2. case value::
- The “value” must bea constant (such as 1, ‘A’, 3), and cannot be a variable (for example, case num will cause an error).
- Each case corresponds to a “possible value of the variable”, for example, case 1: corresponds to the situation where “the variable equals 1”.
๐ 3. break; keyword:
- This is the “soul” of the switch statement! Its function is toexit the entire switch statement, avoiding “fall-through execution” (i.e., executing all subsequent case codes after the current case).
- If break is not written, the program will start executing from the matching case and continue downwards until it encounters a break or the end of the switch, which is usually not what we want!
๐ 4. default::
- It is equivalent to the else in if-else if-else, serving as a “fallback” option, executing the code in default when the variable does not match any case values.
- The position of default is not fixed (it can be before or after all cases), but it is usually placed last, and it is recommended to add break.
- Default is optional; if all possible values of the variable are covered by cases (for example, days 1-7), default can be omitted.
(3) Execution Logic (Three-Step Method)
Taking “determining the day of the week” as an example, suppose day=3:
1ใ๐ฉ Step One: switch(day) retrieves the variable value 3 and enters the switch statement;2ใ๐ Step Two: Compare the case values one by one – case 1 (3โ 1), case 2 (3โ 2), case 3 (3=3), find the matching case 3, and execute the code under case 3 (output “Wednesday”);3ใ๐ช Step Three: Execute the break; under case 3, exiting the switch statement, and the entire process ends.
If case 3 does not have a break:
- After executing the code of case 3, it will continue to execute case 4, case 5โฆ until it encounters a break or the end of the switch, leading to the output “Wednesday, Thursday, Fridayโฆ”, resulting in a logical error!
3. ๐ Programming Case Studies – From Basic to Practical Value Matching Scenarios
Case 1: Determining the Day of the Week (Basic Application)
Write a program that allows the user to input the day number (1-7) and outputs the corresponding day name:
#include <iostream>using namespace std;int main() { int day; cout << "Please enter the day number (1=Monday, 2=Tuesday...7=Sunday):"; cin >> day; switch (day) { case 1: cout << "Today is Monday, starting a new week!" << endl; break; case 2: cout << "Today is Tuesday, keep it up!" << endl; break; case 3: cout << "Today is Wednesday, halfway through the week!" << endl; break; case 4: cout << "Today is Thursday, just two more days to go!" << endl; break; case 5: cout << "Today is Friday, looking forward to the weekend!" << endl; break; case 6: cout << "Today is Saturday, time to relax!" << endl; break; case 7: cout << "Today is Sunday, prepare for next week's study!" << endl; break; default: cout << "Input error! The day number can only be 1-7!" << endl; break; } return 0;}
๐ Run Scenario 1 (Input 5):
Please enter the day number (1=Monday, 2=Tuesday...7=Sunday):5
Today is Friday, looking forward to the weekend!
โ Run Scenario 2 (Input 8):
Please enter the day number (1=Monday, 2=Tuesday...7=Sunday):8
Input error! The day number can only be 1-7!
๐ Case Explanation: Each case corresponds to a day number, and default handles invalid input, with break ensuring each case exits after execution, maintaining clear logic!
Case 2: Simple Menu System (Practical Scenario)
Write a program to simulate a “Student Information Management System” menu, where the user inputs an option number to execute the corresponding function:
#include <iostream>using namespace std;int main() { int choice; // Display menu cout << "===== Student Information Management System =====" << endl; cout << "1. Query Student Grades" << endl; cout << "2. Modify Student Information" << endl; cout << "3. Add New Student" << endl; cout << "4. Exit System" << endl; cout << "==========================" << endl; cout << "Please enter your choice (1-4):"; cin >> choice; switch (choice) { case 1: cout << "\nQuerying student grades..." << endl; cout << "Xiao Ming: Math 95, Chinese 88" << endl; break; case 2: cout << "\nModifying student information..." << endl; cout << "Xiao Hong's age has been changed from 10 to 11" << endl; break; case 3: cout << "\nAdding new student..." << endl; cout << "New student added: Xiao Gang, age 9" << endl; break; case 4: cout << "\nThank you for using! The system has exited!" << endl; break; default: cout << "\nInput error! Please select an option between 1-4!" << endl; break; } return 0;}
๐ Run Result (Input 2):
===== Student Information Management System =====
1. Query Student Grades
2. Modify Student Information
3. Add New Student
4. Exit System
==========================
Please enter your choice (1-4):2
Modifying student information...
Xiao Hong's age has been changed from 10 to 11
๐ Case Explanation: The switch perfectly fits the “menu option” value matching scenario, making the code more concise than if-else if-else, resulting in a better user experience!
Case 3: Using “Fall-Through” to Simplify Code (Advanced Technique)
Sometimes, you can intentionally omit break to use “fall-through” to let multiple cases execute the same code (for example, “Monday to Friday are school days”):
#include <iostream>using namespace std;int main() { int day; cout << "Please enter the day number (1-7):"; cin >> day; cout << "Today needs to:"; switch (day) { case 1: case 2: case 3: case 4: case 5: // From Monday to Friday, the following code will execute (because the previous cases have no break) cout << "School, doing homework" << endl; break; case 6: case 7: // From Saturday to Sunday, execute the following code cout << "Rest, playing games" << endl; break; default: cout << "Input error!" << endl; break; } return 0;}
๐ Run Result (Input 3):
Please enter the day number (1-7):3
Today needs to: School, doing homework
๐ Run Result (Input 6):
Please enter the day number (1-7):6
Today needs to: Rest, playing games
๐ Case Explanation: Cases 1-4 do not have break, so they will “fall through” to case 5, executing “School, doing homework”; similarly, case 6 falls through to case 7, executing “Rest, playing games”, simplifying repetitive code (no need to write the same output in each weekday case)!
4. โ ๏ธ Common Mistakes and Pitfall Avoidance Techniques
โ Error 1: Using a floating-point number as the switch variable (causing a compilation error)
double price = 3.5;switch (price) { // Error: switch variable cannot be double/float case 3.5: cout << "Price 3.5 yuan"; break;}
๐ Problem: Floating-point numbers have precision errors (for example, 3.5 may actually be stored as 3.499999999), making it impossible to match case values accurately; C++ does not allow switch variables to be floating-point numbers.
โ Solution: If you need to check floating-point numbers, use if-else if-else; if itโs a monetary value, convert it to an integer (for example, convert 3.5 yuan to 35 jiao, using int type).
โ Error 2: Using a variable as the case value (causing a compilation error)
int num = 2;int day = 2;switch (day) { case num: cout << "Tuesday"; break; // Error: case value must be a constant}
๐ Problem: The case value must be a “constant that can be determined at compile time” (such as 1, 5, ‘A’), and cannot be a variable (the value of num may change at runtime).
โ Solution: Use a constant instead of a variable, such as const int num = 2; (a variable modified by const is a constant), or directly write case 2:.
โ Error 3: Forgetting to write break leads to “fall-through execution”
int choice = 1;switch (choice) { case 1: cout << "Querying grades"; // No break case 2: cout << "Modifying information"; // Will be executed break;}
๐ Run Result: Querying grades Modifying information (both case codes executed).
๐ Problem: Case 1 does not have a break, so after executing, it continues to execute case 2’s code, leading to a logical error.
โ Solution: Except in scenarios where fall-through is intentionally utilized, every case (including default) must have a break; develop the habit of “adding break after writing a case”.
โ Error 4: Duplicate case values (causing a compilation error)
int day = 3;switch (day) { case 3: cout << "Wednesday"; break; case 3: cout << "Wednesday"; break; // Error: case values cannot be duplicated}
๐ Problem: In the same switch, case values must be unique; duplicate values will prevent the compiler from determining which case to match.
โ Solution: Remove duplicate cases, ensuring each value appears only once.
โ Error 5: Incorrect position of default (leading to logical confusion)
int day = 8;switch (day) { default: cout << "Input error"; break; case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break;}
๐ Run Result: Input error (correct, because day=8 does not match any case).
๐ Problem: Although the logic is correct when default is placed first, it does not conform to the conventional thinking of “matching cases first, then fallback to default”, resulting in poor code readability.
โ Solution: Place default at the end of all cases, following the logical order of “first value matching, then fallback”.
5. ๐ข Next Lesson Preview: For Loop (The “Looping Tool” that allows the program to repeatedly execute code)
In this lesson, we learned how to use the switch statement to handle “value matching” scenarios, such as determining the day of the week and menu selection. However, if we need to make the program “repeat a segment of code” (for example, “output numbers 1-10”, “calculate the sum of 1+2+โฆ+100”, or “print ‘I love programming’ 5 times”), using branching statements would require writing a lot of repetitive code.
In the next lesson, we will learn about the for loop – it allows the program to “repeat a block of code a specified number of times”, enabling us to output all numbers from 1-100 with just 3 lines of code, without writing 100 lines of cout!
The for loop is a core tool for “automating repetitive operations” in programming, such as “refreshing enemies 10 times” in games or “accumulating 100 numbers” in calculations, looking forward to exploring it together in the next lesson!๐
