c / expert
Snippet
Manual Loop Unrolling via Duff's Device
Duff's Device is a famous technique relying on legal C syntax where a `switch` statement interleaves directly into a `do-while` loop. It achieves manual loop unrolling with minimal branch condition evaluation overhead. The `switch` jumps into the middle of the unrolled block to handle remainder elements, and execution continues into the loop construct seamlessly.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>#include <stddef.h>void duff_copy(char *to, const char *from, size_t count) {if (count == 0) return;size_t 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);}}int main(void) {const char src[] = "DuffsDeviceUnrollingTest";char dest[30] = {0};duff_copy(dest, src, sizeof(src));printf("Copied string: %s\n", dest);return 0;}
Breakdown
1
size_t n = (count + 7) / 8;
Calculates total number of unrolled iterations needed for groups of 8 operations.
2
switch (count % 8) {
Jumps to the precise fall-through case matching remainder elements before full loop iterations start.
3
case 0: do { *to++ = *from++;
Interleaves do-while iteration boundary with switch label 0 to begin cyclic execution.