Explanation, please!

Chris Torek chris at mimsy.UUCP
Thu Aug 25 17:16:15 AEST 1988


In article <638 at paris.ICS.UCI.EDU> schmidt at bonnie.ics.uci.edu (Douglas
C. Schmidt) writes:
>The following piece of wonderful obscurity comes from Stroustup's
>C++ Programming Language book, page 100:

>   switch(count % 8) {
>      case 0:  do { *to++ = *from++;
>      case 7:       *to++ = *from++;
	...
>      case 1:       *to++ = *from++;
>               } while (--n > 0);
>   }

>Now, much to my surprise, this is not only valid C++, it is also valid C!
>Could some one please explain to me why this is so?  It seems like
>the case 7-1 labels are actually nested inside the do {} while loop,
>and thus not in the scope of the switch (should a break statement exit
>both the switch and the loop, or just one?!?!).

`break' exits the innermost switch or loop, hence a `break' in cases
7 through 1 exits the do-while, not the switch.

>Finally, Stroustrup asks the rhetorical question ``why would anyone
>want to write something like this.''  Any guesses?!

This has been called `Duff's device' (after Tom Duff, who probably did
not invent it first), and it looks exactly like what an optimising
compiler generates when it does loop unrolling.  It works because case
labels are just that---labels.  As long as there is a switch in
scope, a case label is legal; the case applies to the closest switch.
(And if C had used a separate keyword for `break switch', the whole
thing could be consistent :-) .)

Why?  To quote a certain infamous C language hack :-) , `It looks exactly
like what an optimising compiler generates when it does loop unrolling.'

Incidentally, there are some compilers that choke on that form.  I
would have to look hard at the dpANS to decide whether it is Officially
Legal.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list