An amusing piece of code

Robert Vetter robertv at tekla.UUCP
Mon Apr 7 09:36:57 AEST 1986


In article <1370 at ism780c.UUCP> tim at ism780c.UUCP (Tim Smith) writes:
>Here is an amusing piece of code that someone who wants to remain
>annonymous invented.
>
>The situation is that we have something that, if written with if-then-else
>would be
>
>	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:
>
>	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.
>
>
>-- 
>
>Tim Smith       sdcrdcf!ism780c!tim || ima!ism780!tim || ihnp4!cithep!tim
>
>PS: I bet you were relieved that I didn't say you invented this, right Darryl?



	Why not : 


	switch ( thing ) {
            case A:         A-code;
                            break;

            case B:         B-code;
		            BCD-common-code();
                            break;

            case C:         C-code;
		            BCD-common-code();
                            break;

            case D:         D-code;
		            BCD-common-code();
                            break;

            case E:         E-code;
	}
	

	It's structured and readable.


Rob Vetter
(503) 629-1291
[ihnp4, ucbvax, decvax, uw-beaver]!tektronix!tekla!robertv

"Waste is a terrible thing to mind" - NRC
  (Well, they COULD have said it)



More information about the Comp.lang.c mailing list