Good code for sometimes shared case stuff
Bradford S. Werner
bsw9370 at ritcv.UUCP
Fri Apr 11 03:56:20 AEST 1986
>In posting<1370 at ism780c.UUCP>, Tim Smith asks about a switch with common
>code for some cases. I have seen two solutions.
>1) put the common code in a subroutine
> 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; break;
> }
I can't seem to find the original so maybe this is senseless, but did anyone
else out there get the same impression I did: it seemed to me that there
was not a question as to C implementation, but a query for some construct
which C does not support to more cleanly handle such instances?
There have been mentions of gotos, functions, and booleans to handle the code,
all which introduce unnecessary complexity to this code:
gotos -- are difficult for structure checkers to tie
down semantically
functions -- remove code (maybe only used in this switch)
from the forefront, retracting clarity
booleans -- with additional control structures break up the
code less than retreat into functions, but still
cloud the flow
So, assuming that anyone is interested in non-C solutions, how about:
<<Wearing ring of fire resistance on left hand.>>
switch(thing) {
case A: A-code; break;
switch same { /* use same expression, maybe just "switch" */
case B: B-code; continue; /* continue down to default? */
case C: C-code; continue;
case D: D-code; continue;
default: BCD-common-code(); break(2); /* ick, maybe tagged? */
}
case E: E-code; break;
}
and while I'm at it... a structure for loops where it's necessary to check
whether there've been any trips through the loop. It might not read too
well, because I though of it while using (gak) Fortran.
loop(initial;while-condition;inter-trip;any-trips-after;no-trips){
code
}
(by the way, trip==iteration) where the first three expressions of the
structure are consistent with the for construct, and the last two to be
evaluated depending on whether any iterations were done -- maybe useful
for a context-sensitive while-condition for which you'd rather not assign
to a temporary (the language processor does that) for readability or
optimization reasons. This is similar to:
BOOL any_trips = FALSE;
for(initial;while-condition;inter-trip){
code
any_trips = TRUE; /* not an int because of poss. oflo */
}
if(any_trips)
any-trips-after;
else
no-trips;
Does anyone out there think that these constructs are useful, and please
don't just say that they aren't minimal, or aren't C, or can't be done
otherwise, because C isn't minimal either, and (correct me if I'm wrong)
isn't discussion of additives to C in the scope of this newsgroup?
Bradford S. Werner
bsw9370 at ritcv.UUCP
More information about the Comp.lang.c
mailing list