Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84 exptools; site ho95e.UUCP Path: utzoo!watmath!clyde!burl!ulysses!mhuxr!mhuxt!houxm!ho95e!wcs From: wcs@ho95e.UUCP (#Bill_Stewart) Newsgroups: net.lang.c Subject: Re: An amusing piece of code Message-ID: <638@ho95e.UUCP> Date: Wed, 9-Apr-86 17:33:03 EST Article-I.D.: ho95e.638 Posted: Wed Apr 9 17:33:03 1986 Date-Received: Fri, 11-Apr-86 00:56:31 EST References: <1370@ism780c.UUCP> <2600044@ccvaxa> Reply-To: wcs@ho95e.UUCP (Bill Stewart 1-201-949-0705 ihnp4!ho95c!wcs HO 2G202) Organization: AT&T Bell Labs, Holmdel NJ Lines: 59 In article <2600044@ccvaxa> aglew@ccvaxa.UUCP writes: >>/* Written 10:10 pm Apr 4, 1986 by tim@ism780c.UUCP in ccvaxa:net.lang.c */ >>[Describes a code structure that looks reasonably ugly with if-then-elses] >>[I'll include it at the bottom of this letter for reference] >>We would like to use a switch for everything. Here is a solution: [ugly switch statement] >>Noone here has been able to come up with a reasonable style for this. The >>example above is not to bad, but if B-code, C-code, etc, are complicated, >>then it starts to get ugly. > [Back to Andy Glew:] >May I make a modest suggestion? The above code is a classic example of >converging flows of control. Write it: > > switch ( thing ) { > case A: A-code; break; > > case B: B-code; goto BCDcode; > case C: C-code; goto BCDcode; > case D: D-code; goto BCDcode; > > BCDcode: BCD-common-code; break; > > case E: E-code; break; > } > [Some notes on making it clean and maintainable] >Now, I ask you: which is more easily readable? The goto code, or those if(0) { >abominations in the example above? Or the original if-then-else code, which >I include here? [I'm leaving it out; it really was ugly] >A last word - gotos are often the most elegant means of implementing >complicated structures. Whether you should be using such complicated >structures is another question - for me, finding that I can code >something more cleanly with gotos than with conventional structures >sets the flag . >As well it should. But gotos should not be thrown out. > While I agree with Andy that his goto-code was at least as clean and maintainable as either of the original switch-an-if versions, it's possible to write a relatively clean gotoless version. (Disclaimer: I'm not a purist about gotos, and generally use them when they're cleaner than flag-based code.) /* maybe set BCD_later_flag=FALSE here instead of later */ switch ( thing ) { case A: A-code; BCD_later_flag = FALSE; break case B: B-code; BCD_later_flag = TRUE; break case C: C-code; BCD_later_flag = TRUE; break case D: D-code; BCD_later_flag = TRUE; break case E: E-code; BCD_later_flag = FALSE; break default: default-code; BCD_later_flag = FALSE; } if (BCD_later_flag) { whetever(); } -- # Bill Stewart, AT&T Bell Labs 2G-202, Holmdel NJ 1-201-949-0705 ihnp4!ho95c!wcs