We have seen the use of if,if-else and if-else if-else loops for decision making.If there are too many else if statements the program becomes difficult and cumbersome. For this purpose we use the switch statement to replace multiple else if statements. The basic syntax of a switch statement is as follows:
// code to be executed if a is equal to constant1;
// code to be executed if a is equal to constant2;
// code to be executed if a doesn’t match any constant
Example of a switch statement :
int numberofapples = 2;
case 1: printf(“Number of apples is 1”);
case 2: printf(“Number of apples is 2”);
case 3: printf(“Number of apples is 3”);
default: printf(“Number of apples is not 1 or 2 or 3”);
The default block,as the comment says, is executed if none of the other cases match.This block is optional.
The break keyword at the end of each block causes control to jump to the end of switch statement after that particular block is processed.It is very important to include the break statement after every case or else the condition called “fall through” will occur which basically means even if a particular case is true and that block is executed, if there is no break statement, control will enter all subsequent blocks and execute them all unless a break is encountered.
C++ switch statements support int and char data values.