switch (expression)
Chris Torek
chris at mimsy.UUCP
Fri Jul 15 03:56:21 AEST 1988
In article <7329 at cup.portal.com> Paul_L_Schauble at cup.portal.com writes:
>And while we're at it, seems to me as though the expression in
> switch (Type)
>should allow any Type for which the == operator is defined.
The reason switch works the way it does is that it `wants to'
compile into a computed goto:
switch (i) {
case 1: ... break;
case 2: ... break;
.
.
.
case 37: ... break;
default: ... break;
}
compiles to
reg = i-1
(unsigned)(reg - 36)
>= 0 ? goto default
goto cases[reg]
A more general version appears in Mesa:
SELECT expression FROM
{ expression => statements }*
END
(syntax very approximate). All `expression's are arbitrary; the
language is defined such that the first `expr =>' that matches the
selected expression takes effect. It is up to the optimiser to notice
that all the `expr =>'s are constant (if indeed they are) and turn this
into a computed goto; if some of the `expr's are non-constant, the
whole thing must usually be compiled as a series of if/else tests.
The construct does have some advantages. For instance, instead of
IF bool-exp1 THEN stmts1
ELSE IF bool-exp2 THEN stmts2
ELSE IF bool-exp3 THEN stmts3
.
.
.
ELSE stmtsn
one can write
SELECT TRUE FROM
bool-exp1 => stmts1
bool-exp2 => stmts2
bool-exp3 => stmts3
.
.
.
TRUE => stmtsn
END
and of course a series of `if not bool-exp' statements can be written
even more simply as `SELECT FALSE FROM bool-exp ...' (although then
the `default' must be written `FALSE => ...').
--
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain: chris at mimsy.umd.edu Path: uunet!mimsy!chris
More information about the Comp.std.c
mailing list