The D Programming Language: switches

Barry Margolin barmar at think.COM
Wed Mar 23 02:57:25 AEST 1988


In article <1186 at PT.CS.CMU.EDU> edw at IUS1.CS.CMU.EDU (Eddie Wyatt) writes:
> >>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.
> > 	Theoretically the switch construct is more powerful than an else-if
> > chain because it selects in one step.  Execution is O(1) rather than O(n)
> > where n is the number of branches.  It is, for example, considerably more
> > efficient to use a switch with a thousand cases than an else-if chain with
> > a thousand elses.  [This is not to be taken as an endorsement of such
> > code. :-)]
>  I think he meant in terms of expressability.  Which is true in a
>practical sense, false in theorectically.  'switch' and 'else-if'
>are equivalent in terms of expressability.

That is obviously untrue.  A switch can only check one expression, and
can only compare it against constant values.  An else-if chain can
check for multiple conditions and can compare computed values.  You
can even have side effects in the conditional expressions, which can
affect later conditionals (I don't recommend this practice taken to
extreme, but things like 'if ((ch = getchar()) == EOF) ... else if (ch
== '\n') ...' aren't too bad).

Barry Margolin
Thinking Machines Corp.

barmar at think.com
uunet!think!barmar



More information about the Comp.lang.c mailing list