generalized switch
Dan Tilque
dant at tekla.UUCP
Tue Aug 5 06:17:31 AEST 1986
In article <15120 at ucbvax.BERKELEY.EDU>, kos at ernie.Berkeley.EDU (Joshua Kosman) writes:
>In article <2765 at brl-smoke.ARPA> gwyn at brl.arpa (Doug Gwyn (VLD/VMB) <gwyn>) writes:
>>In article <15093 at ucbvax.BERKELEY.EDU> kos at ernie.Berkeley.EDU (Joshua Kosman) writes:
>>> switch() {
>>> case <boolean-expr>:
>>> etc.
>>> }
>>>...
>>>Any ideas?
>>
>>In C, such code is written:
>>
>> if ( bool_expr_1 )
>> action_1
>> else if ( bool_expr_2 )
>> action_2
>> else if ...
>> else
>> default_action
>>
>>You could come up with some CPP macros for this, but why bother?
>
>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.
>But the switch promotes comprehensibility. The situation I
>find (mildly) frustrating is when I have a choice among cases, a
>setup which is conceptually akin to a switch, but is not
>syntactically equivalent because I want to use a slightly different test
>than simple equality.
>
>
In PL/I this is probably how it is done, but many (if not most) C compilers
convert the switch-case statement to a branch table. (There are also
statements in FORTRAN and COBOL which also convert to branch tables.) A branch
table is just a series of assembler branch instuctions in a row. The
first of these branches jumps to a location within the branch table
based on the switch value times the length of the branch instruction.
The rest of the branches are jumps to code to be executed if the switch
value is 0, 1, 2... The default case must be handled before the branch
table is entered.
If you followed the above explanation, you should understand why the
switch value (as it is currently implemented) has to be an integral
type expression. It's likely that the designer(s) of this statement
had a branch table in mind when the statement was designed.
Branch tables are very efficient if the case values have small gaps
between them, but can be somewhat inefficient otherwise.
=========================================================================
Dan Tilque UUCP: tektronics!dadla!dant
CSnet: dant%dadla at tektronix
ARPAnet: dant%dadla%tektronix at csnet-relay
I can't think of anything clever to put here.
=========================================================================
More information about the Comp.lang.c
mailing list