sort of like this,
#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.Ah okay, thanks! Surprisingly more readable as there's no loop (in this example...)
That isn't Duff's device. Duff's device has NO return/break, it intentionally falls through to the next case statement. It is an interesting optimization that is only rarely useful (and probably even less useful in these days of optimization compilers) that everybody misunderstands.