Does Duff Device break C compilers

"Lambert Lum" <>
6 May 1996 23:18:18 -0400

          From comp.compilers

Related articles
Does Duff Device break C compilers (Lambert Lum) (1996-05-06)
Re: Does Duff Device break C compilers (1996-05-07)
Re: Does Duff Device break C compilers krste@ICSI.Berkeley.EDU (1996-05-08)
Re: Does Duff Device break C compilers (1996-05-10)
Re: Does Duff Device break C compilers (1996-05-10)
Re: Does Duff Device break C compilers (1996-05-10)
Re: Does Duff Device break C compilers (1996-05-13)
[1 later articles]
| List of all articles for this month |

From: "Lambert Lum" <>
Newsgroups: comp.compilers
Date: 6 May 1996 23:18:18 -0400
Organization: Compilers Central
Keywords: C, question

I was reading through the C FAQ, and I saw this really, really unusual
item called a Duff Device. I showed to a couple of guys here at my
work place and they never seen it before. Then they declared that such
an unorthodox technique could potential break some C compilers. Does
it? I don't think so, but would you guys say? For those not familiar
with Duff Device, here is the C FAQ description.

20.35: What is "Duff's Device"?

A: It's a devastatingly deviously unrolled byte-copying loop,
devised by Tom Duff while he was at Lucasfilm. In its "classic"
form, it looks like:

register n = (count + 7) / 8; /* count > 0 assumed */
switch (count % 8)
case 0: do { *to = *from++;
case 7: *to = *from++;
                                case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
} while (--n > 0);

where count bytes are to be copied from the array pointed to by
from to the memory location pointed to by to (which is a memory-
mapped device output register, which is why to isn't
incremented). It solves the problem of handling the leftover
bytes (when count isn't a multiple of 8) by interleaving a
switch statement with the loop which copies bytes 8 at a time.
(Believe it or not, it *is* legal to have case labels buried
within blocks nested in a switch statement like this. In his
announcement of the technique to C's developers and the world,
Duff noted that C's switch syntax, in particular its "fall
through" behavior, had long been controversial, and that "This
code forms some sort of argument in that debate, but I'm not
sure whether it's for or against.")
\\ Emcee Lam <>< \\ Electronics For Imaging (work)
\\ 28269 Peachtree Dr. \\ 2855 Campus Dr.
\\ Hayward, CA 94545 \\ San Mateo, CA 94403-2510
\\ 510/783-4154 \\ 415/286-8333 FAX: 415/286-8545
[I'd be very surprised to find a compiler that didn't handle this correctly.
I first used this hack at least 20 years ago, and it wasn't new then. -John]


Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.