Sometimes, when the IF statement is nested, all if statements look very similar because they are evaluated for an exact same expression, with the only difference being that each if statement compares the result of the expression with a different value. For example:
if (day == 0)
dayName = "Sunday";
else if (day == 1)
dayName = "Monday";
else if (day == 2)
dayName = "Tuesday";
else if (day == 3)
...
else
dayName = "Unknown";
In these cases, it is often necessary to rewrite the nested if statement into a switch statement, making the program more efficient and easier to understand.
Understanding the syntax of a switch statement
The syntax for the switch statement is as follows (Switch,case and default are keywords):
switch ( controllingExpression )
{
case constantExpression :
statements
break;
case constantExpression :
statements
break;
...
default :
statements
break;
}
Controllingexpression (control expression) only one value at a time. Then, starting with the case whose constantexpression value is equal to the Controllingexpression value, all the statements underneath it will run until a break is encountered. The switch statement then ends, and the program continues execution from the first statement after the switch closes the curly brace and ignores the other case.
If any one of the constantexpression values is not equal to the value of controllingexpression, the statement under optional label default is run.
Note that if the value of the controllingexpression does not match any of the case labels, and no default tag is found, the program skips the entire switch statement and continues execution from the first statement after its closing brace.
For example, the preceding nested if statement can be rewritten as the following switch statement:
switch (day)
{
case 0 :
dayName = "Sunday";
break;
case 1 :
dayName = "Monday";
break;
case 2 :
dayName = "Tuesday";
break;
...
default :
dayName = "Unknown";
break;
}