generalized switch
Tainter
tainter at ihlpg.UUCP
Tue Aug 5 08:18:00 AEST 1986
> Sure, that's the way I have been doing it. But you can do that with
> any choice among cases.
> 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.
> Joshua Kosman
> kos at ernie.berkeley.EDU
You are wrong.
switch (a) {
case 'a': hi();
case 'b': ho(); break;
case 'c': he();
case 'd': ha(); break;
}
. . .
can be written as:
if (a == 'a') {
hi(); goto do2; /* skip the test on 2 */
}
if (a == 'b') {
do2:
ho(); goto done; /* do a break */
}
if (a == 'c') {
he(); goto do4; /* skip the test on 4 */
}
if (a == 'd') {
do4:
ha(); goto done; /* do a break */
}
done:
. . .
A bit different than the simple if else block, ja?
The switch statement can also be coded as a jump table with generaly better
performance than the if else block.
It might be feasable to fold if else blocks testing the same variable repeatedly
into a jump table, but I'll wager it's unusual.
--j.a.tainter
More information about the Comp.lang.c
mailing list