An amusing piece of code
aglew at ccvaxa.UUCP
aglew at ccvaxa.UUCP
Sun Apr 6 14:13:00 AEST 1986
>/* 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:
>
> switch ( thing ) {
>case A: A-code; break;
>case B: B-code; if ( 0 ) {
>case C: C-code; if ( 0 ) {
>case D: D-code; }}
> BCD-common-code; break;
>case E: E-code;
> }
>
>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.
I find it amusing to now be in the position of advocating `unstructured'
goto code, since in my last job I was the evangelist of structured programming.
Oh, well, into the fray...
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;
}
Notes: (1) DO NOT cut out the goto BCDcode after D-code. Fall through should
never be used in this type of situation, since it can cause awkward bugs
if the D case gets moved around. (2) I have tried to use the indentation
above to indicate that BCDcode is subordinate to cases B, C, and D.
(3) Try to choose a reasonably meaningful name for the label.
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?
> if ( thing == A )
> A-code;
> else
> if ( thing == B || thing == C || thing == D ) {
> switch ( thing ) {
> case B: B-code; break;
> case C: C-code; break;
> case D: D-code; break;
> }
> BCD-common-code;
> } else
> if ( thing == E )
> E-code;
>
>A, B, C, D, and E are constant expressions, so this is not elegant.
>We would like to use a switch for everything. Here is a solution:
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.
Structured programming != gotoless programming
(Does anybody know Dr. Goto from Japan? I believe he's now a motor behind
the Fifth Generation Computer Project.)
Andy "Krazy" Glew. Gould CSD-Urbana. USEnet: ihnp4!uiucdcs!ccvaxa!aglew
1101 E. University, Urbana, IL 61801 ARPAnet: aglew at gswd-vms
More information about the Comp.lang.c
mailing list