2

Possible Duplicates:
What does this C code do [Duff's device]?
How does Duff's device work?

void duff(register char *to, register char *from, register int count)
{ 
     register int n=(count+7)/8;
     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);
     }
}

Is the above valid C code? If so, what is it trying to achieve and why would anyone do something like the above?

Community
  • 1
  • 1
rrr
  • 39
  • 2
  • 2
    http://stackoverflow.com/questions/1723270/what-does-this-c-code-do-duffs-device http://stackoverflow.com/questions/514118/how-does-duffs-device-work – cnicutar May 26 '11 at 15:20

3 Answers3

8

Yes, it's known as Duff's Device.

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
4

Yes, it is valid C code. It is a clever optimization for copying the correct number of bytes (in count) from one pointer (the from) to another pointer (the to). The switch statement uses fall through on the cases, so case 7: will copy one byte, and then fall through to case 6:. Eventually everything falls through the correct number of copy instructions, resulting in the correct number of bytes being copied. This allows tight packing of the generated assembly instructions on most machines, and generally was seen to improve performance.

You can read more about duff's device here.

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
1

The code is correct, it's known as Duff's Device.

I think the best way to understand how this code works is to understand the work of switch and for that i suggest the following code: look at "case x:" as just simple label

void duff(register char *to, register char *from, register int count)
{ 
     register int n=(count+7)/8;

     // replace switch with this lines 
     if (count % 8 == 7) goto case 7;
     if (count % 8 == 6) goto case 6;
     if (count % 8 == 5) goto case 5;
     if (count % 8 == 4) goto case 4;
     if (count % 8 == 3) goto case 3;
     if (count % 8 == 2) goto case 2;
     if (count % 8 == 1) goto case 1;
     if (count % 8 == 0) goto case 0;
          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);

}

I suggest to visit this link How does Duff's device work?

sorry for my English

Community
  • 1
  • 1
ob_dev
  • 2,808
  • 1
  • 20
  • 26