c / expert
Snippet
Resumable Function Coroutines via Interleaved Switch-Case Statements
By exploiting the standard C grammar rule where case labels can jump into nested loop blocks (derived from Duff's Device principles), lightweight coroutine state machines can yield execution and resume from their precise prior position.
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
27
28
#include <stdio.h>typedef struct {int state;int i;} GeneratorState;int step_generator(GeneratorState *ctx) {switch (ctx->state) {case 0:for (ctx->i = 0; ctx->i < 3; ctx->i++) {ctx->state = 1;return ctx->i * 10;case 1:;}}ctx->state = -1;return -1;}int main(void) {GeneratorState gen = { .state = 0, .i = 0 };int val;while ((val = step_generator(&gen)) != -1) {printf("Yielded: %d\n", val);}return 0;}
Breakdown
1
switch (ctx->state)
Jumps directly to the saved execution state marker within the generator context upon re-entry.
2
case 1:;
Acts as an internal jump target inside the loop body, bypassing loop re-initialization when resuming.