C++ switch Statement
The switch statement is a control structure in C++ that allows a program to execute different blocks of code based on the value of a variable. The syntax of the switch statement is as follows:
switch (expression) { case value1: // Code to execute when expression == value1 break; case value2: // Code to execute when expression == value2 break; ... default: // Code to execute when expression does not match any of the values break; }Sourw:ecww.theitroad.com
The expression is a variable or expression whose value will be compared against the different case values. If the value of the expression matches one of the case values, the corresponding code block is executed. The optional default
case is executed when the expression does not match any of the case values.
Here's an example of a switch statement:
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; default: cout << "Invalid day" << endl; break; }
In this example, the variable day
is equal to 3, so the code block associated with the case value 3
is executed, and the message "Wednesday" is printed to the console.
Note that each case block ends with a break
statement. This is because without a break
statement, control will "fall through" to the next case block, which is not what we want in most cases. The break
statement causes the program to exit the switch statement and continue executing code after the switch statement.
Also note that the switch statement only works with integer and character data types. It does not work with floating-point types or strings.