C++ Switch Case
Switch Statement in C++:
In C++, the switch
statement is used for decision-making based on the value of an expression. It provides a way to execute different code blocks for different values of the expression. Here's the basic syntax:
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// ... additional cases
default:
// Code to execute if expression doesn't match any case
}
Here's an example illustrating the use of the switch
statement:
#include <iostream>
int main() {
char grade;
std::cout << "Enter your grade (A, B, C, D, or F): ";
std::cin >> grade;
switch (grade) {
case 'A':
std::cout << "Excellent!" << std::endl;
break;
case 'B':
std::cout << "Good job!" << std::endl;
break;
case 'C':
std::cout << "Satisfactory." << std::endl;
break;
case 'D':
std::cout << "Needs improvement." << std::endl;
break;
case 'F':
std::cout << "Failed." << std::endl;
break;
default:
std::cout << "Invalid grade." << std::endl;
}
return 0;
}
In this example, the program prompts the user to enter a grade (A, B, C, D, or F). The switch
statement then checks the value of the grade
variable and executes the corresponding code block.
A few key points about the switch
statement:
- Each
case
must end with abreak
statement to exit theswitch
block. Withoutbreak
, the control will "fall through" to the nextcase
. - The
default
case is optional and is executed if none of thecase
values match the expression. - The expression within the
switch
statement can be of integral or enumerated type. C++17 allows usingswitch
withstd::string
.
It's worth noting that switch
statements are often used when there are multiple values to check against a single expression. If you're dealing with ranges or more complex conditions, if-else if-else
statements might be more suitable.