C++ Switch
The switch
statement in C++ provides a way to execute different blocks of code based on the value of a variable or expression. It is especially useful when you have multiple possible conditions to check against a single variable.
1. Basic Switch Statement
The basic syntax of the switch
statement:
#include <iostream>
int main() {
int day = 3;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
case 4:
std::cout << "Thursday" << std::endl;
break;
case 5:
std::cout << "Friday" << std::endl;
break;
default:
std::cout << "Weekend" << std::endl;
}
return 0;
}
2. Using Switch with Enum
You can use switch
with enum types:
#include <iostream>
enum class Direction {
Up,
Down,
Left,
Right
};
int main() {
Direction dir = Direction::Left;
switch (dir) {
case Direction::Up:
std::cout << "Going Up" << std::endl;
break;
case Direction::Down:
std::cout << "Going Down" << std::endl;
break;
case Direction::Left:
std::cout << "Going Left" << std::endl;
break;
case Direction::Right:
std::cout << "Going Right" << std::endl;
break;
default:
std::cout << "Unknown Direction" << std::endl;
}
return 0;
}
3. Switch Fallthrough
C++ allows fallthrough behavior in switch cases by omitting the break
statement:
#include <iostream>
int main() {
int num = 2;
switch (num) {
case 1:
std::cout << "One" << std::endl;
// No break, falls through to next case
case 2:
std::cout << "Two" << std::endl;
break;
case 3:
std::cout << "Three" << std::endl;
break;
default:
std::cout << "Other" << std::endl;
}
return 0;
}
Conclusion
The switch
statement in C++ provides an efficient way to handle multiple possible conditions for a single variable or expression. This chapter covered the basic syntax of switch
, its usage with enum types, and the concept of fallthrough behavior. Understanding how to effectively use switch
statements allows you to write clearer and more structured code, especially in scenarios where you need to evaluate multiple cases.