Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!caip!sri-spam!parcvax!hplabs!tektronix!teklds!dadla!tekla!dant From: dant@tekla.UUCP (Dan Tilque) Newsgroups: net.lang.c Subject: Re: generalized switch Message-ID: <696@tekla.UUCP> Date: Mon, 4-Aug-86 16:17:31 EDT Article-I.D.: tekla.696 Posted: Mon Aug 4 16:17:31 1986 Date-Received: Tue, 5-Aug-86 23:09:02 EDT Organization: Tektronix, Inc., Beaverton, OR Lines: 60 Keywords: switch In article <15120@ucbvax.BERKELEY.EDU>, kos@ernie.Berkeley.EDU (Joshua Kosman) writes: >In article <2765@brl-smoke.ARPA> gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) writes: >>In article <15093@ucbvax.BERKELEY.EDU> kos@ernie.Berkeley.EDU (Joshua Kosman) writes: >>> switch() { >>> case : >>> 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@tektronix ARPAnet: dant%dadla%tektronix@csnet-relay I can't think of anything clever to put here. =========================================================================