Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/5/84; site ism780c.UUCP Path: utzoo!watmath!clyde!burl!ulysses!bellcore!decvax!hplabs!sdcrdcf!ism780c!tim From: tim@ism780c.UUCP (Tim Smith) Newsgroups: net.lang.c Subject: Re: An amusing piece of code Message-ID: <1723@ism780c.UUCP> Date: Tue, 15-Apr-86 16:34:12 EST Article-I.D.: ism780c.1723 Posted: Tue Apr 15 16:34:12 1986 Date-Received: Thu, 17-Apr-86 05:29:24 EST References: <1370@ism780c.UUCP> <360@hadron.UUCP> Reply-To: tim@ism780c.UUCP (Tim Smith) Organization: Interactive Systems Corp., Santa Monica, CA Lines: 61 In article <360@hadron.UUCP> jsdy@hadron.UUCP (Joseph S. D. Yao) writes: > >Assuming that you can't put BCD-common-code into a function, I >agree with everyone else that you should use [forward-referencing!] >goto's here, and [again] cite Prof. Knuth's _Structured_Programming_ >_with_Goto's_. One major problem is that this code jumps into blocks >[the effect of case C: and case D: ]. This is something that X3J11 >warns about. I thought K&R did, too; but I can't find it. It is >generally a bad practice, although most compilers seem to allow it >without too much trouble. At least in one case, jumping into blocks has been blessed by DMR, so I am not too worried about that. The problem with the goto versions is that one then has to think of a name for the label, and make sure one uses the same name in two places. Yuck-o! Here is a suggested form that should satisfy the goto supporters, and still not make me have to think of a name for the label: #define GOTO_THERE if(0){ #define THERE } switch(v) { case A; A-code; break; case B; B-code; GOTO_THERE; case C: C-code; GOTO_THERE; case D: D-code; THERE; /* the ; looks sort of like a : */ THERE; BCD-common-code; break; case E: E-code; break; } In real programs, one might have several groups of cases, each with different common code. Most of the methods suggested can get kind of ugly, with gotos all over the place. I think the best way is to probably have two switches, one after the other: switch(v) { case A: A-code; break; case B: B-code; break; case C: C-code; break; case D: D-code; break; case E: E-code; break; } /* * handle common code */ switch(v) { case B: case C: case D: BCD-common-code(); break; } This can be easily expanded, and I think it is pretty readable. Not that it can be expanded with a third switch to handle a third level of common code, etc. -- Tim Smith sdcrdcf!ism780c!tim || ima!ism780!tim || ihnp4!cithep!tim