3

Possible Duplicate:
How does Duff's device work?

I am trying to understand how this is working. Any help would be appreciated.

#include<stdio.h>

void duff(int count)
  {
      int n=(count+7)/8;
      printf("n=%d  count =%d\n",n,count%8);
      switch(count%8){
      case 0: do{ printf("case 0\n");
      case 7:  printf("case 7\n");
      case 6: printf("case 6\n");
      case 5: printf("case 5\n");
      case 4: printf("case 4\n");
      case 3: printf("case 3\n");
      case 2: printf("case 2\n");
      case 1: printf("case 1\n");
              }while( --n >0);
      }
  }

main(){
int count;
scanf("%d",&count);
duff(count);

}

Basically if the switch case evaluates to case statement 2, then the do statment of the while is never executed. But i ran this program and it gave me the output, but unable to explain:
output:

3
n=1 count =3
case 3
case 2
case 1

Community
  • 1
  • 1
Pkp
  • 929
  • 6
  • 19
  • 31

3 Answers3

3

This is known as duff's device and is used in code optimization techniques to reduce branch instructions. The reason that it works is that by default case statements without breaks fall through to the next case so when you hit case 3, you keep going through to case 2 and case 1.

Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88
1

Both the do and the case "statements" are essentially just "goto labels". They don't add any actual code. They just tell while and switch (respectively) where to jump to. In other words, there is no code for the do to (not) execute.

(That said, it is somewhat remarkable/bizarre that C's grammar allows cases to exist in children of the switch, rather just as direct children of a switch.)

Laurence Gonsalves
  • 137,896
  • 35
  • 246
  • 299
  • Being that they are goto labels, it's nothing special.. – R.. GitHub STOP HELPING ICE Mar 07 '12 at 07:15
  • @R.. Do you use any languages other than C and C++? In any language, the equivalent of a switch-case or a the beginning of a loop becomes the equivalent of a goto label, but other languages with structured control flow typically do not allow loops and switches to be interleaved in this way. Similarly, the beginning of the "else" branch of an if statement is essentially a goto label, but C doesn't let you have a loop that starts in the "if" part and ends in the "else" part. – Laurence Gonsalves Mar 07 '12 at 17:11
  • I didn't mean on some abstract level they're like goto; of course that's true of any control construct in any language. I was speaking specifically of C and the fact that, in the language itself, they're treated the same as goto labels. – R.. GitHub STOP HELPING ICE Mar 07 '12 at 18:07
0

There are no break statements between the cases so the cases fall through. Therefore n=3 causes case 3: case 2: and case 1: to be executed.

twain249
  • 5,666
  • 1
  • 21
  • 26