switch
In C++, the switch statement is a control flow structure that allows you to execute one block of code out of many based on the value of a variable or expression. It's often used as an alternative to long chains of if-else if statements when you need to compare the same variable to different values.
The Structure of a switch Statement
The basic syntax of a switch statement is as follows:
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
...
default:
// Code to execute if expression does not match any case
}
- expression: This is the variable or value that is evaluated.
- case value1, value2, ...: These are the possible values of the expression. Each case represents a different potential match.
- break: This keyword is used to exit the switch statement after a case is executed. Without break, the program will continue to execute the subsequent cases, a behavior known as "fall-through."
- default: The default block is optional and executes if none of the specified cases match the expression. It acts as a catch-all.
Example 1: Basic switch Statement
Let's look at a simple example where a switch statement is used to print the name of the day based on a number input.
#include <iostream>
using namespace std;
int main() {
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day number" << endl;
}
return 0;
}
Explanation:
- Here, day is the expression evaluated by the switch statement.
- If day is 3, the program prints "Wednesday" and then exits the switch statement due to the break.
- If day is not between 1 and 7, the default case will execute, printing "Invalid day number."
Example 2: Omitting the break Statement (Fall-through)
If the break statement is omitted, the program continues executing the subsequent cases, even if they don't match the expression
#include <iostream>
using namespace std;
int main() {
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
case 2:
cout << "Tuesday" << endl;
case 3:
cout << "Wednesday" << endl;
case 4:
cout << "Thursday" << endl;
case 5:
cout << "Friday" << endl;
case 6:
cout << "Saturday" << endl;
case 7:
cout << "Sunday" << endl;
default:
cout << "Invalid day number" << endl;
}
return 0;
}
Explanation:
- In this example, because the break statements are omitted, if day is 3, the program will print "Wednesday," "Thursday," "Friday," "Saturday," "Sunday," and "Invalid day number."
- This behavior is often undesirable but can be useful in specific scenarios.
Example 3: Grouping Cases
You can group multiple cases together if they should result in the same outcome.
#include <iostream>
using namespace std;
int main() {
char grade = 'B';
switch (grade) {
case 'A':
case 'B':
case 'C':
cout << "You passed!" << endl;
break;
case 'D':
case 'F':
cout << "You failed." << endl;
break;
default:
cout << "Invalid grade" << endl;
}
return 0;
}
Explanation:
- In this example, if grade is 'A', 'B', or 'C', the program will print "You passed!"
- If grade is 'D' or 'F', the program will print "You failed."
- The default case handles any invalid grades.
When to Use switch Statements
Use a switch statement when:
- You have a single variable or expression to evaluate.
- You need to compare the variable or expression against multiple specific values.
- You want a cleaner and more readable structure than a long series of if-else if statements.
Avoid using a switch statement if:
- You need to compare ranges of values (e.g., if (x > 5)).
- Your cases are based on complex conditions or expressions.
Summary
- The switch statement provides a clean and efficient way to handle multiple potential values of a variable or expression.
- Each case in a switch represents a different potential match, and the default case handles any unmatched values.
- Remember to use break to avoid fall-through behavior unless it is intentionally desired.
Practice Problems
- Write a program that converts a number between 1 and 12 into the corresponding month of the year using a switch statement.
- Create a program that takes a character input from the user and tells them if it's a vowel or a consonant using a switch statement.
- Write a program that simulates a simple calculator. The user should input two numbers and an operator (+, -, *, /), and the program should output the result using a switch statement.
This content provides a thorough explanation of the switch statement in C++, including examples, when to use it, and practice problems to help solidify the understanding of this control flow structure.