The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly.
You can use one switch statement inside another switch statement so switch can be nested only once.
The construction
switch (expression)
{
case const-expr: statements
case const-expr: statements
case const-expr: statements
default: statements; break;
}
Each case is labeled by one or more integer-valued constants or constant expressions. If a case matches the expression value, execution starts at that case. All case expressions must be different. The case labeled default is executed, if none of the other cases are satisfied. A default is optional; if it isn’t there and if none of the cases match, no action at all takes place.
Example
#include <stdio.h> int Program_A() { printf("Program A \n"); } int Program_B() { printf("Program B \n"); } int Program_C() { printf("Program C \n"); } int main() { int selection; printf("Options: \n"); printf("1.Program A \n"); printf("2.Program B \n"); printf("3.Program C \n"); printf("Please select \n?"); scanf("%d", &selection); switch (selection) { case 1: Program_A(); break; case 2: Program_B(); break; case 3: Program_C(); break; default: printf(" You did not make a right choice!"); break; } return 0; }
The break statement causes an immediately exit from the switch. Because cases serve just as labels, after the code for one case is done, execution falls through to the next unless you take explicit action to escape. Break and return are the most common ways to leave the switch. A break statement can also be used to force an immediate exit from while, for and do -while loops.
As a matter of good form, put a break after the last case (the default here) even though it’s logically unnecessary. Some day when another case gets added at the end, this bit of defensive programming will save you.
NOTE! Exercises for that chapter can be found in quizzes Exercises 4 and P3-4 where these skills will also be tested. It is also important that the student does these examples above.