c / expert
Snippet
Stateful Re-entrant Coroutine Trampoline via Switch Fallthrough State Machine
This snippet demonstrates stackless coroutines in C built upon switch-statement state persistence. By utilizing macro expansion and the built-in __LINE__ preprocessor directive, execution resumes at the exact line of the previous yield point upon subsequent function invocations.
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
#include <stdio.h>typedef struct {int state;int index;} GeneratorState;#define COROUTINE_BEGIN(ctx) switch((ctx)->state) { case 0:#define COROUTINE_YIELD(ctx, val) do { (ctx)->state = __LINE__; return (val); case __LINE__:; } while(0)#define COROUTINE_END(ctx) default: (ctx)->state = -1; return -1; }int generate_fibonacci(GeneratorState *ctx) {static int a = 0, b = 1;COROUTINE_BEGIN(ctx);while (ctx->index < 5) {int next = a + b;a = b;b = next;ctx->index++;COROUTINE_YIELD(ctx, a);}COROUTINE_END(ctx);}
Breakdown
1
#define COROUTINE_BEGIN(ctx) switch((ctx)->state) { case 0:
Opens a switch block jumping directly to the saved state integer inside the context object.
2
#define COROUTINE_YIELD(ctx, val) do { (ctx)->state = __LINE__; return (val); case __LINE__:; } while(0)
Saves current source line as resume target state, returns a value, and provides a case label for re-entry.
3
COROUTINE_YIELD(ctx, a);
Yields control back to caller while preserving execution position for next iteration.
4
#define COROUTINE_END(ctx) default: (ctx)->state = -1; return -1; }
Closes the trampoline construct and sets state to invalid upon completion.