A switch statement allows you to control the flow of your program similar to if and else statements, but can be easier for the user to understand.
The Switch Statement
The structure of a switch statement is the following:
switch(expression) {
case :
statements
break;
case :
statements
break;
//More cases...
default :
statements
}
The case to be executed is determined based on the value of the constant_expression. In other words, you may have an int, char, etc…They must be constants. The break statement once encountered breaks out of the switch statement. In other words, if you don’t include the break statement in one of your cases, it will simply execute the following cases until it reaches a break or the end of switch statement. The default case is simply all other cases not covered.
An example would be…
cin >> number;
switch(number) {
case 1:
cout << "One\n";
break;
case 2:
case 3:
cout << "My favorite numbers...\n";
break;
default:
cout << "What!?\n";
}
In other words, if the user chooses 1, they will encounter case 1, if they choose 2 or 3, they receive "My favorite..." statement, else they receive "What!?".
Another example comparing an if else statement with a switch statement
Imagine a banking program in which the teller gives the program an integer value to perform a different action. Each action determines the reward the user receives.
1 - Gold Reward... Receives $100 reward plus all the other rewards
2 - Silver Reward... Received $50 reward plus the Bronze Reward
3 - Bronze Reward... Received $25 reward
* - Deduct $100 from their account
*Denotes any other value
How would this look like with a if and else statement?
cin >> action;
if ( action == 1 ) {
//Give Gold Award
//Give Silver Reward
//Give Bronze Reward }
else if ( action == 2 ) {
//Give Silver Reward
//Give Bronze Reward }
else if ( action == 3 ) {
//Give Bronze Reward }
else {
//Deduct $100 from their account }
}
What about with a switch statement?
cin >> action;
switch(action) {
case 1:
//Give Gold Reward
case 2:
//Give Silver Reward
case 3:
//Give Bronze Reward
break;
default:
//Deduct $100 from their account
}
In other words, once action satisfies one case, it keeps executing the statements until it reaches the break statement which breaks out of the switch statement. Wouldn't this be much easier to for a reader to understand? Most likely in certain cases.
