A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
In C, case labels are just labels. They can appear anywhere inside the switch body, including inside loops, if statements, and nested blocks. The switch jumps to the matching label and execution continues sequentially, regardless of the surrounding control structure. This is legal. It is also how Duff's Device works: a loop unrolling trick that interleaves switch cases inside a do-while loop. It is clever, confusing, and almost never the right choice in modern code.
#include <stdio.h>void duffs_copy(const int *src, int *dst, int count) {int n = (count + 7) / 8;switch (count % 8) {case 0: do { *dst++ = *src++;case 7: *dst++ = *src++;case 6: *dst++ = *src++;case 5: *dst++ = *src++;case 4: *dst++ = *src++;case 3: *dst++ = *src++;case 2: *dst++ = *src++;case 1: *dst++ = *src++;} while (--n > 0);}}int main(void) {int src[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int dst[10] = {0};duffs_copy(src, dst, 10);printf("Copied: ");for (int i = 0; i < 10; i++) printf("%d ", dst[i]);printf("\n");return 0;}
The switch jumps into the middle of the do-while loop based on count % 8. The first iteration handles the remainder. Subsequent iterations fall through all eight cases. The loop unrolls eight copies per iteration, reducing loop overhead. This was a genuine performance optimization on 1980s hardware. On modern CPUs with branch predictors and optimizing compilers, it is unnecessary. The compiler unrolls loops for you at -O2.
The code is correct. It is also nearly unreadable. A reviewer must understand switch fall-through, do-while semantics, and the interaction between the two to verify it. A bug in the case ordering or the loop condition is almost invisible. Modern compilers generate equivalent or better code from a simple for loop. The cleverness has no payoff. Write the simple loop. Let the compiler be clever.
#include <stdio.h>void simple_copy(const int *src, int *dst, int count) {for (int i = 0; i < count; i++) {dst[i] = src[i];}}int main(void) {int src[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int dst[10] = {0};simple_copy(src, dst, 10);printf("Copied: ");for (int i = 0; i < 10; i++) printf("%d ", dst[i]);printf("\n");return 0;}
Duff's Device is a historical curiosity and an interview question. It demonstrates the power and the danger of C's label semantics. In production code, write the simple loop. The compiler will optimize it. The reviewer will understand it. The maintainer will not curse you. Next: void functions as a design pattern, and when returning nothing is the right choice.
Finish the lesson once you have worked through the material. This awards ★ 40 XP.