An amusing piece of code

Tim Smith tim at ism780c.UUCP
Wed Apr 16 07:34:12 AEST 1986


In article <360 at hadron.UUCP> jsdy at 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



More information about the Comp.lang.c mailing list