Explanation, please!
Henry Spencer
henry at utzoo.uucp
Sat Aug 27 05:01:36 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...
Tom Duff, what hast thou wrought? :-)
>...
>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?!?!).
You're thinking of switch as if it were Pascal's case; the correct model
is closer to Fortran's computed goto. The labels must appear within the
case body, but they can be (essentially) *anywhere* within the body,
including within nested blocks. The sensible programmer will not exploit
this freedom except in truly unusual situations, but it is available.
Break breaks out of the innermost construct that it could apply to, i.e.
"just one".
>Finally, Stroustrup asks the rhetorical question ``why would anyone
>want to write something like this.'' Any guesses?!
This construct is called "Duff's Device", after its discoverer. One can
often make a loop run faster by "unrolling" it, duplicating its body
N times and running one-Nth as many iterations -- this reduces the loop-
control overhead by a factor of N. The annoying part is that the number
of times one needs to do the body is usually not an even multiple of N,
so one has to do a partial iteration at beginning or end. The usual
assembly-language trick is to compute a start address in the middle
of the loop and start by branching there, not to the beginning, thus
doing a partial iteration first. Most high-level languages have no way
to express this. Tom Duff (of Bell Labs) realized that it could be done
in C. Ugh.
--
Intel CPUs are not defective, | Henry Spencer at U of Toronto Zoology
they just act that way. | uunet!attcan!utzoo!henry henry at zoo.toronto.edu
More information about the Comp.lang.c
mailing list