c / expert
Snippet
Cooperative Coroutine Yielding via Switch Case Fallthrough State Machines
Demonstrates asymmetric coroutine yielding in standard C using switch case statement mechanics (similar to Duff's Device). The function persists its internal state across invocations, re-entering execution directly inside the loop structure.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>typedef struct {int state;int index;} Coroutine;int process_stream(Coroutine* cr, const int* buffer, int size) {switch (cr->state) {case 0:for (cr->index = 0; cr->index < size; cr->index++) {cr->state = 1;return buffer[cr->index];case 1:;}}cr->state = -1;return -1;}
Breakdown
1
switch (cr->state)
Jumps directly to the saved execution label inside the function upon re-entry.
2
cr->state = 1;
Updates the internal state instance marker immediately prior to yielding execution.
3
return buffer[cr->index];
Yields the current value back to the caller while suspending function execution.
4
case 1:;
Acts as an interleaved jump destination target located directly inside the body of the for-loop.