Expert C Programming

(Jeff_L) #1

case 2


case 3


case 4


default


This is known as "fall through" and was intended to allow common end processing to be done, after
some case-specific preparation had occurred. In practice it's a severe misfea-ture, as almost all case


actions end with a break;. Most versions of lint even issue a warning if they see one case falling


through into another.


Software Dogma


Default Fall Through Is Wrong 97% of the Time


We analyzed the Sun C compiler sources to see how often the default fall through was used.
The Sun ANSI C compiler front end has 244 switch statements, each of which has an
average of seven cases. Fall through occurs in just 3% of all these cases.


In other words, the normal switch behavior is wrong 97% of the time. It's not just in a
compiler—on the contrary, where fall through was used in this analysis it was often for
situations that occur more frequently in a compiler than in other software, for instance,
when compiling operators that can have either one or two operands:


switch( operator->num_of_operands ) {


case 2: process_operand( operator->operand_2 );


/ FALLTHRU /


case 1: process_operand( operator->operand_1 );


break;


}


Case fall through is so widely recognized as a defect that there's even a special comment
convention, shown above, that tells lint "this really is one of the 3% of cases where fall
through was desired." The inconvenience of default fall through is borne out in many other
programs.


We conclude that default fall through on switches is a design defect in C. The overwhelm-ing majority
of the time you don't want to do it and have to write extra code to defeat it. As the Red Queen said to
Alice in Through the Looking Glass, you can't deny that even if you used both hands.


Another Switch Problem—What Does break

Free download pdf