Is this essentially the mechanism behind Duff's Device (switch cases being better thought of as line-oriented jumps instead of structured blocks) but generalised?
#include <stdio.h>
static int generator(int st, float *out) {
switch (st++) {
case 0: *out = 1.0f; return st;
case 1: *out = 7.0f; return st;
case 2: *out = 9.0f; return st;
}
return 0;
}
int main(void) {
float f;
for (int st = 0; (st = generator(st, &f));) {
printf("generator yielded %g\n", (double)f);
}
return 0;
}
but notice you also have the option to make the state static rather than a parameter, which gives you more encapsulation of your state machine at the cost of being way less flexible in terms of threading and reentrance.
sort of like this,
but notice you also have the option to make the state static rather than a parameter, which gives you more encapsulation of your state machine at the cost of being way less flexible in terms of threading and reentrance.