Skip to:

Duff's Device

A "Duff's device" is a rather dramatic use of fall through in C switch statments that is used to implement partial loop unrolling by interlacing the structures of a switch and a loop. It was first proposed as a way to optimize a copy to an I/O port by Tom Duff way back in 1983 while he was working at Lucasfilm.

Many people have complained (and still) complain that the worst feature of C is that switches don't break automatically before each case label. As Tom says, "This code forms some sort of argument in that debate, but I'm not sure whether it's for or against.". Opinion aside however this is legal ANSI C and is also legal C++ for that matter (it makes an appearance in Bjarne Stroustrup's book).

Here is the example from Tom's original announcement. Think about it carefully...

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);
}
 

Company Registration