The D Programming Language: switches

Karl Heuer karl at haddock.ISC.COM
Mon Mar 21 08:04:04 AEST 1988


In article <941 at micomvax.UUCP> ray at micomvax.UUCP (Ray Dunn) writes:
>Case statements should just be generalised into a "shorthand" way of
>stating if...elseif...elseif...else...

I disagree.  The else-if chains already provide a perfectly good way of doing
that, and are just as concise.  There's no need to add a second syntax of
equivalent power.  In fact, the existing switch statment is more concise in
the job for which it was designed: you can write "case VALUE:" instead of
"case (long_hairy_expression == VALUE):".  If the controlling expression has
side effects, your "enhanced" switch would require an extra temporary.

Yes, in a sense switch is less powerful than an else-if chain.  Let's keep it,
for the same reasons that we retain flow constructs less powerful than goto.

The existing switch isn't perfect, of course.  I do think we should get rid of
automatic fallthrough, and allow a list of values (or a list of ranges) for
each label.  Then the case-blocks would be commutative.

>Compilers can easily generate just as "efficient" code when only constant
>expression values are involved

Oh?  Do any compilers currently optimize if-else statements in this way?

>(MSC 4.0 seems to generate worse code when you use a case statement than when
>you use an if...else if...else... sequence!).

A compiler that doesn't optimize the existing switch is unlikely to do
anything intelligent with the generalization.

Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint



More information about the Comp.lang.c mailing list