C++ switch statement
Created By: chatGPT
The switch statement in C++ is a control structure that allows the execution of different parts of code based on the value of a variable. It acts as a more efficient alternative to using a series of if-else statements when checking a variable against many constant values. Here’s the syntax for a switch statement:
switch (expression) {
case constant1:
// Code to be executed if expression equals constant1
break;
case constant2:
// Code to be executed if expression equals constant2
break;
// Add more cases as needed
default:
// Code to be executed if none of the cases match
}
A break statement is essential in each case. Without it, the program will continue executing the next case (this is called fall-through behavior). Using a default case is optional but recommended for handling unexpected values. Here's a complete example to illustrate how the switch statement works:
In this example, the value of day is checked in the switch statement. If it equals 3, "Wednesday" is assigned to dayName and printed to the console. If an invalid number is provided (for example, 8), the default case will be executed, showing "Invalid day." This structured approach helps in maintaining clean, readable code when handling multiple conditions.#include <iostream>
int main() {
int day = 3;
std::string dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
std::cout << "Day: " << dayName << std::endl;
return 0;
}