Newsgroups: comp.lang.c Path: utzoo!henry From: henry@utzoo.uucp (Henry Spencer) Subject: Re: Explanation, please! Message-ID: <1988Aug26.190136.24977@utzoo.uucp> Organization: U of Toronto Zoology References: <638@paris.ICS.UCI.EDU> Date: Fri, 26 Aug 88 19:01:36 GMT In article <638@paris.ICS.UCI.EDU> schmidt@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@zoo.toronto.edu