Notes
Detailed Notes on Switch Statements in C++
What is a Switch Statement?
A switch statement is a control structure in C++ used to compare a single value against multiple possible cases, making it a more efficient and readable alternative to using multiple if-else if statements. It is especially useful when you need to compare a variable to many possible values.
Why Use a Switch Instead of Multiple if-else if Statements?
Using multiple if-else if statements to compare the same variable against many values can be inefficient and hard to read, especially when there are many comparisons. A switch statement simplifies the code and makes it more readable by directly comparing the variable against multiple cases.
Example of Inefficient if-else if Chain:
if (month == 1) {
// January
} else if (month == 2) {
// February
} else if (month == 3) {
// March
}
// Continue for all months
This approach can become difficult to manage and understand when there are numerous comparisons.
Switch Statement Syntax:
The syntax for a switch statement is as follows:
switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
// Additional cases as needed
default:
// Code to execute if no case matches
}
- switch (expression): The expression is the value you’re comparing against multiple possible cases.
- case value: Each
casechecks if the expression matches a specific value. If it matches, the code inside that case block is executed. - break: After a case block executes, the
breakstatement ensures the program exits the switch statement, preventing the execution of subsequent cases. - default: The
defaultcase executes when none of thecasevalues match the expression. It is similar to theelsestatement in anif-elsechain.
Example 1: Month Name Based on Input
Here’s an example where we prompt the user for a month number (1-12) and display the corresponding month name:
#include <iostream>
using namespace std;
int main() {
int month;
cout << "Enter the month number (1-12): ";
cin >> month;
switch (month) {
case 1: cout << "It is January"; break;
case 2: cout << "It is February"; break;
case 3: cout << "It is March"; break;
case 4: cout << "It is April"; break;
case 5: cout << "It is May"; break;
case 6: cout << "It is June"; break;
case 7: cout << "It is July"; break;
case 8: cout << "It is August"; break;
case 9: cout << "It is September"; break;
case 10: cout << "It is October"; break;
case 11: cout << "It is November"; break;
case 12: cout << "It is December"; break;
default: cout << "Please enter a number between 1 and 12."; break;
}
return 0;
}
Explanation:
- The program asks for the month number.
- The
switchstatement checks the month number and displays the corresponding month. - The
defaultcase handles invalid input (e.g., numbers outside the range 1-12).
Output Examples:
- Input: 4 → Output: “It is April”
- Input: 12 → Output: “It is December”
- Input: -42 → Output: “Please enter a number between 1 and 12.”
Example 2: Letter Grade Based Message
Here’s another example where we use a switch statement to print a message based on the user’s letter grade (A, B, C, D, or F):
#include <iostream>
using namespace std;
int main() {
char grade;
cout << "Enter your letter grade (A-F): ";
cin >> grade;
switch (grade) {
case 'A': cout << "You did great!"; break;
case 'B': cout << "You did good."; break;
case 'C': cout << "You did okay."; break;
case 'D': cout << "You did not do good."; break;
case 'F': cout << "You failed."; break;
default: cout << "Please only enter a letter grade A through F."; break;
}
return 0;
}
Explanation:
- The program asks for the letter grade.
- The
switchstatement checks the grade and prints the corresponding message. - The
defaultcase handles invalid input (e.g., if the user enters a non-grade letter).
Output Examples:
- Input: ‘A’ → Output: “You did great!”
- Input: ‘F’ → Output: “You failed.”
- Input: ‘Z’ → Output: “Please only enter a letter grade A through F.”
Advantages of Using Switch Statements:
- Efficiency: Switch statements are faster than multiple
if-elsechains when checking for many possible values, because the switch is optimized by the compiler to compare the value directly rather than checking each condition sequentially. - Readability: Switch statements make code easier to read, especially when you have multiple conditions to check.
- Simplicity: Instead of writing multiple
else ifstatements, you can condense them into a single switch statement.
Default Case:
The default case is optional but can be very useful. It ensures that if none of the case values match the expression, a message or alternative action is executed. It’s essentially the “catch-all” for unmatched conditions.
Example of Default Case:
In the month example, the default case handles cases where the user inputs a number that is not between 1 and 12. It provides feedback to the user to enter a valid value.
Best Practices:
- Order of cases: Switch statements compare the expression against each case from top to bottom. Thus, the order of cases does matter. The first match is executed, and the remaining cases are skipped.
- Break statement: Always remember to use
breakafter each case to prevent “fall-through.” Without it, once a case matches, the program will continue to execute the next case’s code, which is often not desired. - Character Comparison: Switch cases can compare characters and integers, but not ranges. Each case must represent a specific value.
- Avoid using
switchfor floating-point values: C++ doesn’t support usingswitchwithfloatordoubletypes due to precision issues.
Conclusion:
The switch statement is a powerful and efficient control structure in C++ used to compare a single variable against many values. It’s particularly helpful when you have a large number of possible conditions to check, making your code cleaner and easier to manage than using multiple if-else statements. Whether you’re checking months, letter grades, or other values, switch statements simplify your decision-making logic.