The switch statement causes a particular group of statements to be chosen from several available groups. The selection is based upon the current value of an expression which is included within the switch statement.
This is another from of the multi way decision. It is well structured, but can only be used in certain cases where; only one variable is tested, all branches must depend on the value of that variable. The variable must be an integral type. (Int, long, short, or char). Each possible value of the variable can control a single branch. A final, catch all, default branch may optionally be used to trap all unspecified cases. The general of switch statement is:
Switch (expression)
{
case val – 1:
statement block – 1;
break;
case val – 2:
statement block – 2;
. . . . . .
. . . . . .
default:
default – block;
break;
}
next – statement;
The expression is an integer expression or character. Val – 1, Val – 2…. Are constants or constants expressions and they know as case labels.
When a switch statement is executed, the switch expression is successively compared with the case labels. If match, the corresponding statements – block is executed. The break statement at the end of each case signals the end of a particular case and causes an exit from the switch statement. The default case label is optional. If it presents, then it will be executed if the value of the expression does not match with any of the case values. If not present, no action takes place and control transferred to the next statement. Figure 5.5 shows the logic of execution of switch statement.
For example:
Scanf (“%d”, & number);
Switch (number)
{
case 0:
printf(“none\n”);
break;
case 1:
printf (“one\n”);
break;
case 2 :
printf (“two\n”);
break;
case 3:
case 4:
case 5:
printf (“several\n”);
break;
default:
printf(“many\n”);
break;
}
Each interesting case is listed with a corresponding action. The break statement prevents any further statements from being executed by leaving the switch. Since case 3 and case 4 have no following break, they continue on allowing the same action for several values of number.
Both if and switch constructs allow the programmer to make a selection from a number of possible actions.
About the Author
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc