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.
void main (void)
unsigned short int myVal = 0;
printf (“myVal is 1\n”);
break; /* mandatory to put break. This makes the program go to the next line out of switch statement */
printf (“myVal is 2\n”);
printf (“myVal is 3\n”);
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:
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:
printf(“ myVal is not in the range 1...3\n”);
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...