For example:
int getNext(int n) {
while (TRUE) {
n = n+1;
yield n;
}
}
int main() {
while (TRUE) {
int n = getNext(1);
if (n > 42)
break;
printf("%d\n",n);
}
}
Such that the above code would print all numbers from 1 to 42.
I thought of making yield
change the address of getNext to the instruction after yield
. But I cant figure out how I would save the context (registers/variables) since the stack would be ran over by the caller function.
Note:
I realize that the code above can be easily implemented by static variables, but that's not the point.
<ucontext.h>
maybe. – Octagonyield
style iterators need some restructuring of the code to turn it a state machine (unless you want to play stupid tricks with the stack, that is). Are you only interested in simple cases like the one in the question, where that isn't a concern? – Poppyheadyield
. I'd love to be proved wrong. – Bacteriostatstatic
variable is that you can't have more than one generator running at the same time (and if you want to restart it, things get ugly). It's conceptually awful, and in practice it only works for simple use cases. – Poppyhead