An amusing piece of code

#Bill_Stewart wcs at ho95e.UUCP
Thu Apr 10 08:33:03 AEST 1986


In article <2600044 at ccvaxa> aglew at ccvaxa.UUCP writes:
>>/* Written 10:10 pm  Apr  4, 1986 by tim at 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 <There is probably something wrong with this algorithm>.
>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



More information about the Comp.lang.c mailing list