Switch Case

A switch case allows a variable to be test equally against a list of values. Each value is called a case, and the variable being switched to each switch case.

Syntax:
switch(expression)
{
case constant-expression  :
statements;
break; /* optional */
case constant-expression  :
statements;
break; /* optional */
/* you can have any number of case statements */
default: /* Optional */
statements;
}

The following rules apply to a switch case

• Must have an integral or enumerated type

• You can have any number of case statements within a switch.

• When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

• When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch case.

• Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

• The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Example
int main ()
{
char grade = ‘B’;
switch(grade)
{
case ‘A’ :
printf(“Excellent!\n” );
break;
case ‘B’ :
case ‘C’ :
printf(“Good\n” );
break;
case ‘D’ :
printf(“Passed\n” );
break;
case ‘F’ :
printf(“Better try again\n” );
break;
default :
printf(“Invalid grade\n” );
}
return 0;
}

Advantages of Switch over if-else
• To minimize the execution time required for if/else tests one needs to put more likely cases first. With switch/case programmer doesn’t need to think about this.

• With if/else default case must be at the very end i.e. after last else. In switch – default can be anywhere.

• Switch proves better option than if-else statement where we need to execute common code for several conditions. Just omitting ‘break’ in switch.

Leave a Reply