Expert C Programming

(Jeff_L) #1

Another problem is that any statements inside a switch can be labelled and jumped to, allowing
control to be passed around arbitrarily:


switch (i) {


case 5+3: do_again:


case 2: printf("I loop unremittingly \n"); goto do_again;


default : i++;


case 3: ;


}


The fact that all the cases are optional, and any form of statement, including labelled statements, is
permitted, means that some errors can't be detected even by lint. A colleague of mine once mistyped


defau1t for the default label (i.e., mistyped a digit "1" for the letter "l"). It was very hard to track


this bug down, and it effectively removed the default case from the switch statement. However, it still
compiled without errors, and even a detailed review of the source showed nothing untoward. Most
lints don't catch this one.


By the way, since the keyword const doesn't really mean constant in C,


const int two=2;


switch (i) {


case 1: printf("case 1 \n");


case two: printf("case 2 \n");


error ^^^ integral constant expression expected


case 3: printf("case 3 \n");


default: ; }


the code above will produce a compilation error like the one shown. This isn't really the fault of the
switch statement, but switch statements are one place the problem of constants not being constant
shows up.


Perhaps the biggest defect in the switch statement is that cases don't break automatically after the
actions for a case label. Once a case statement is executed, the flow of control continues down,
executing all the following cases until a break statement is reached. The code


switch (2) {


case 1: printf("case 1 \n");


case 2: printf("case 2 \n");


case 3: printf("case 3 \n");


case 4: printf("case 4 \n");


default: printf("default \n");


}


will print out

Free download pdf