Case-control statement – Switch
The control statement that allows us to make a decision from the number of choices is called a switch, or more correctly a switch-case-default since these three keywords go together to make up the control statement. A Switch is a composite statement used to make a decision between many distinct alternative possibilities of a constant presence in a variable or yielded from an expression. The syntax is as follows:
switch ( integer expression )
{
case constant 1 :
do this ;
case constant 2 :
do this ;
case constant 3 :
do this ;
default :
do this ;
}
The integer expression following the keyword switch is any C expression that will yield an integer value. It could be an integer constant like 1, 2 or 3, or an expression that evaluates to an integer. The keyword case is followed by an integer or a character constant. Each constant in each case must be different from all the others. The “do this” lines in the above form of switch represent any valid C statement.
A default label is a special form of the case label. It is executed whenever none of the other case values matches the value in the switch expression. Note, however, that default is not mandatory.
The need for a break
switch (i)
{
case 1: printf("It is 1\n");
case 2: printf("It is 2\n");
case 3: printf("It is 3\n");
default: printf("None of the above");
}
The output of the above program is:
It is 1
It is 2
It is 3
None of the above
Clearly, this is not the desired output. The desired output is just “It is 1”. The program prints case 2 and 3 and the default case. It is important to note that it is the responsibility of the programmer to break out of the switch block once the intended case is executed. The following snippet illustrates the same:
switch (i)
{
case 1: printf("It is 1\n"); break;
case 2: printf("It is 2\n"); break;
case 3: printf("It is 3\n"); break;
default: printf("None of the above");
}
Note that there is no need for a break statement after the last statement (in this case, the default statement) since the control comes out of the switch anyway. The operation of the switch is shown below in the form of a flowchart for a better understanding.
Points to note
- Cases can be sorted in any order. Not necessarily in incremental order as shown in previous examples. But note that it is advised to keep a logical order and the default statement at the beginning or at the end for better readability of the program written. The following switch snippet is equally valid and does the same job:
switch (i)
{
case 3: printf("It is 3\n"); break;
case 1: printf("It is 1\n"); break;
default: printf("None of the above"); break;
case 2: printf("It is 2\n");
}
- One can use char values in a case as internally they are integer values mapping to ASCII table. The following snippet shows how this is done:
char ch = 'A';
switch (ch)
{
case 'A': printf("Apple\n"); break;
case 'B': printf("Ball\n"); break;
default: printf("None of the above"); break;
case 'C': printf("Cat\n");
}
Output:
Apple
- char values in switch cases can be used interchangeably with their
corresponding integer values. This is illustrated in the following snippet:
char ch = 'A';
switch (ch)
{
case 65: printf("Apple\n"); break;
case 'B': printf("Ball\n"); break;
default: printf("None of the above"); break;
case 'C': printf("Cat\n");
}
- At times we may want to execute a common set of statements for multiple cases. How this can be done is shown in the following example.
char ch = 'A';
switch (ch)
{
case 'a':
case 'A': printf("Apple\n"); break;
case 'b':
case 'B': printf("Ball\n"); break;
default : printf("None of the above"); break;
case 'c':
case 'C': printf("Cat\n");
}
In the above snippet, the output remains the same regardless of the case of the character. Here, we are making use of the fact that once a case is satisfied the control simply falls through the case till it doesn’t encounter a break statement.
- Even if there are multiple statements to be executed in each case there is no need to enclose them within a pair of braces (unlike if, and else).
- Every statement in a switch must belong to some case or the other. If a statement doesn’t belong to any case the compiler won’t report an error. However, the statement would never get executed. For example, in the following program the printf( ) never goes to work.
char ch = 'A';
switch (ch)
{
printf("Inside switch");
case 'A': printf("Apple\n"); break;
case 'B': printf("Ball\n"); break;
default: printf("None of the above"); break;
case 'C': printf("Cat\n");
}
- If we have no default case, then the program simply falls through the entire switch and continues with the next instruction (if any,) that follows the closing brace of the switch, practically producing no effect.
- The disadvantage of the switch is that one cannot have a case in a switch which looks like case i <= 20 :
This is why a switch is not entirely replaceable with the if family of control statements. Even float is not allowed in the switch. The advantage of switch over if is that it leads to a more structured program and the level of indentation is manageable, more so if there are multiple statements within each case of a switch.
- switch works faster than an equivalent if-else ladder. Because the compiler generates a jump table for a switch during compilation. As a result, during execution, it simply refers to the jump table to decide which case should be executed, rather than actually checking which case is satisfied. As against this, if-elses are slower because they are evaluated at execution time. If on the other hand the conditions in the if-else were simple and less in number then if-else would work out faster than the lookup mechanism of a switch. Hence a switch with two cases would work slower than an equivalent if-else. Thus, you as a programmer should take a decision on which of the two should be used when.
- We can check the value of any expression in a switch. Thus the following switch statements are legal
switch ( i + j * k )
switch ( 23 + 45 % 4 * k )
switch ( a < 4 && b > 7 )
Expressions can also be used in cases provided they are constant expressions. Thus, case 3 + 7 is correct, however, case a + b is incorrect.
- The break statement when used in a switch takes the control outside the switch. However, the use of continue will not take control at the beginning of the switch as one is likely to believe.
- In principle, a switch may occur within another, but in practice, it is rarely done. Such statements would be called nested switch statements.
- The switch statement is very useful while writing menu-driven programs.
Exercises
- Write a program that tests the value of an integer num1. If the value is 10, square num1. If it is 9, read a new value into num1. If it is 2 or 3, multiply num1 by 99 and print out the result.
- Write a function called day_of_week that given an integer between 0 and 6, prints the corresponding day of the week. Assume that the first day of the week
(0) is Sunday. - Write a function called month_of_year that, given an integer between 1 and 12, prints the corresponding month of the year.
- Write a function called parkingCharge that, given the type of the vehicle (c for car, b for bus, t for truck) and the hours a vehicle spent in the parking lot, returns the parking charge based on the rates shown below:
a. car : $2 per hour.
b. bus : $3 per hour.
c. truck : $4 per hou