C Language

Give Me a Break

As W. A. Wulf put it, "More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity." C's switch statement could be the all-time award winner in the "stupid efficiency" category. The error in the following code fragment may be obvious outside the context of a larger program; but in real programs, such errors are easy to make and hard to find.

 switch (color) {
   case 1: printf("red\n");
   case 2: printf("blue\n");
 }

Given this code, when color is 1, both "red" and "blue" are printed. The proper code is

 switch (color) {
   case 1: printf("red\n");
        break;
   case 2: printf("blue\n");
 }

Of course, when you add another color, you'd better add another break after the second case. C's switch is not what is generally recognized as a "case" multiway conditional control structure; it's nothing more than a jump table. The compiler evaluates the switch expression simply to determine the target of a jump (i.e., go to) operation into the code that follows. Unless you code a break, execution will continue sequentially through the code for cases that follow the case that matches the switch expression value.

The switch statement may be a honey of an operation for writing small, fast device drivers, but it can be a sticky mess for typical business programming. Code that intentionally jumps into the middle of a sequence of operations is extremely tricky to maintain, and you should avoid it except in low-level systems programs. Fortunately, there's a very simple rule for business (and most other) programmers to follow: Never use the C switch statement.

This stricture is not at all burdensome. As I indicated, most instances of C's switch should have a break after every case. For such multiway conditions, you can simply use an "else if" structure instead:

 if   (color == 1) {
      printf("red\n");
 }
 else if (color == 2) {
      printf("blue\n");
 }
 else {
      printf("Invalid color\n");
 }

Better yet, you can use the EQ macro described in the last installment and the macros presented above (IF, THEN, ELSEIF, ELSE, and ENDIF) to code the tests as in Figure 3.1. This solution has a compact, table-oriented layout and avoids the hazards of raw C.

Figure 3.1 - Coding an ELSEIF in C with Macros

 IF  color EQ 1 THEN printf("red\n");
 ELSEIF color EQ 2 THEN printf("blue\n");
 ELSE            printf("Invalid color\n");
 ENDIF

by BrainBellupdated
Advertisement: