Image

Imageangelbob wrote in Imagecpp

Duff's Device

So here's a trivia item of the day. A few of you may have already heard of Duff's Device, named after its creator, Tom Duff. For those of you who haven't:

void duff_device_demo(int ctr) {
  switch(ctr % 3) {
    while(ctr > 0) {
      printf("%d", ctr);
      ctr--;
  case 2:
      printf("%d", ctr);
      ctr--;
  case 1:
      printf("%d", ctr);
      ctr--;
  case 0:
   }
  }
}


Wacky, yeah? Notice how the while loop is inside the switch statement, but the cases are inside the while loop. The odd thing is that this is fully legal ANSI C (or ISO C, for non-US folks :-). Works fine in C++, too. While CodeWarrior doesn't support certain cases because of funky things they do with switch statements, most compilers (VC++, GCC) support it with nary a complaint, as they should.

The key to understanding it is to realize that a switch is the same as a set of if and goto statements. Once the goto's done, the loop takes over. The thing above is basically a 3-at-a-time loop unroll, but it's all done in C instead of assembly. Neat!

Exercise of the day: where would this control structure be useful. Can you think of a time you'd want to use it in production code?

Incidentally, I have used this in production code, and it was even a good fit for what I used it for. Every new structure you learn is one more time you can use the Right Thing when the opportunity presents itself...