generalized switch

Barry Margolin barmar at mit-eddie.MIT.EDU
Mon Aug 4 15:51:19 AEST 1986


In article <15120 at ucbvax.BERKELEY.EDU> kos at ernie.Berkeley.EDU.UUCP (Joshua Kosman) writes:
>As I understand it, a switch/case setup compiles exactly the same as
>	if (var == const1) {.....};
>	else if (var == const2) {.....};
>	else  {default_action};
>anyway. (Or am i wrong?). In any case, it can be rewritten that way.
>But the switch promotes comprehensibility. The situation I
>find (mildly) frustrating is when I have a choice among cases, a
>setup which is conceptually akin to a switch, but is not
>syntactically equivalent because I want to use a slightly different test
>than simple equality.

One of the features of the switch statement is that you don't have to
write the variable being tested repeatedly.  This helps avoid errors (a
rare safety feature in C).  Also, if your switch is over an expression
the compiler takes care to evaluate it once, so that the programmer
doesn't have to use an explicit temporary.  And, as someone else already
pointed out, since the cases are required to be constants the construct
can be optimized into a jump table.

The generalized switch statement you ask for has none of these features.
All it does is allow you to type "case <exp>:" instead of "else if
<exp>".  A saving of two characters per case seems like a silly reason
to complicate the language.

It might, however, be reasonable to extend the case statement to not
require all the cases to be constants.  This would still provide the
first two features I listed; the compiler would have to do a bit more
work to determine if the construct can be translated into a jump table.
-- 
    Barry Margolin
    ARPA: barmar at MIT-Multics
    UUCP: ..!genrad!mit-eddie!barmar



More information about the Comp.lang.c mailing list