Today I wanted to attract your attention to a funky contraption which dates from the 80′s, and no, it has no connection to Homer’s favourite brand of beer.

I am talking about a nice exploit of the C programming language, related to the case-label fall-through invented by Tom Duff. This function performs the simple task of copying data from one place to another in memory.

send(to, from, count)
register short *to, *from;
register count;
{
    register 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);
    }
}

In the dawn of C and compiler optimization, this function performed almost twice as fast as the naive looping approach due to the loop unrolling (unwinding).

Nowadays it is probably nothing more than a curiosity as memcopy is doing a better job on almost all platforms. Actually at some point the performance of XFree86 got a serious boost from replacing all Duffs. At least one good thing came from the awkward behaviour of C’s switch-case…