Next: while loop Up: Decisions Previous: else-if

switch

Used to perform an -way branch where the decision tests if an expression has one of a finite number of constant values. Its syntax is easily seen with an example.

Suppose char letter has been assigned a single alphabetic character, which is supposed to be A, B or C.

switch (letter)
   {
   case 'A' :   /* do something about A */
                break;

   case 'B' :   /* do something about B */
                break;

   case 'C' :   /* do something about C */
                break;

   default:     /* exception handling */
                printf("Not a valid letter\n");
   }

There are several things to note here.

1. Each allowed value is introduced with a case followed by the actual value (and this is why the expression must have a finite number of constant values).

2. The group of cases is enclosed in braces.

3. Each case effectively acts as a label only: control will drop through unless you explicitly break out of the switch statement.

4. There is a special label, default, which picks up all other cases: this can be left out if appropriate.

5. cases and default can be written in any order.

6. cases must all be different.

It is generally bad practice to rely on falling through a case statement to the next statement. If you have to do so, always comment it clearly. There is one fall-through which is quite common, namely using a switch to identify a range:

switch (letter)
   {
   case 'A':   /* FALL THROUGH */
   case 'B':   /* A or B */
                         break;

   case 'C':             /* C */
                         break;

   default:              /* anything else */
                         break;

   }

In the above, we fell through the `A' case to the `B' case.



Next: while loop Up: Decisions Previous: else-if


maspjw@
Tue Sep 27 15:29:34 BST 1994