Get the latest tech news

Duff's Device and Coroutines (2008)


On Duff's Device and Coroutines Posted on Wednesday, January 30, 2008. At first glance, Duff's Device is one of the most mysterious pieces of C code you'll ever see: void send(short *to, short *from, int count) { 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); } } It's an 8x-unrolled while loop interlaced with a switch statement.

In 2000, Simon Tatham wrote about a C coroutine implementation based on this idea, to make callback-based event-driven programming easier. A switch-based implementation has the advantage of being portable and relatively simple to emit using preprocessor macros, though it doesn't allow the use of other switch statements in the code. A year ago, I asked Duff if that kind of coroutine implementation is what he had in mind, and he confirmed that it was, pointing at a blog comment and adding:

Get the Android app

Or read this on Hacker News

Read more on:

Photo of device

device

Photo of Coroutines

Coroutines

Photo of Duff

Duff

Related news:

News photo

Overseas Galaxy Z Flip 6 and Fold 6 leak parades each device in several colors

News photo

Rabbit R1 AI Device Exposed by API Key Leak

News photo

NTT Data and Zebra Technologies partner on private 5G and device as a service