The D Programming Language: switches
Richard Harter
g-rh at cca.CCA.COM
Wed Mar 23 10:23:12 AEST 1988
In article <18377 at think.UUCP> barmar at fafnir.think.com.UUCP (Barry Margolin) writes:
>> > 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).
We're talking apples, oranges, and pears, here. The switch
construct is superior to the else-if chain in computational efficiency,
in the sense that it can select between n alternatives in one step
rather than n steps, when the selection is made on the value of a
variable which has a range of length n. An else-if chain can be
replaced by successive switches or by a single switch contained within
a while loop (in C with no additional if's), e.g.
more = 1;
kludge = 0;
while (more) switch(kludge) {
case 0: kludge += (1 + (expr1));
break;
case 1: kludge = 3;
break;
case 2: action1;
more = false;
break;
case 3: kludge += (1 + (expr2));
....
[This code does not have the good programming stamp of approval.] If
we ignore questions of computational power and simply consider expressive-
ness, else-if chains can obviously replace switches. And, of course,
if we program reasonably, we use each where it is appropriate. (Easier
said then done.)
--
In the fields of Hell where the grass grows high
Are the graves of dreams allowed to die.
Richard Harter, SMDS Inc.
More information about the Comp.lang.c
mailing list