Interview Questions

C - Switch case statements

We saw the use of if...else... statements in the first round. We will see switch()...case in this chapter. Remember that it can only be used to compare values of variables and choices it can take.

#include<stdio.h>

void main (void)
{
        unsigned short int myVal = 0;
       
        switch (myVal)
        {
                case 1:
                        printf (“myVal is 1\n”);
                        break;  /* mandatory to put break. This makes the program go to the next line out of switch statement */
                case 2:
                        printf (“myVal is 2\n”);
                        break;
                case 3:
                        printf (“myVal is 3\n”);
                        break;
                default:  /* gets executed ONLY when NONE of the case statement is TRUE. */
                        printf(“nothing compared to TRUE\n”);
        }
        printf (“ out of switch...case... \n”);
       
}  /* end of main block */

Output of the program is like this:

nothing compared to TRUE
out of switch...case...

Here in the above program if you forget to place a break in any one case statement, rest of the lines following until it reaches break are executed. Like this:

switch (myVal)
{
        case 1:
        case 2:
        case 3:
                printf(“ myVal is not in the range 1...3\n”);
                break;
        default:
                printf(“myVal is 0\n”);
}

Here we are comparing the values for 1...3 consecutively as the program has a logic of taking same action for values 1 to 3. This reduces repetitive statements for each case statement and is also a good programming practice.

Let us C more...