Take for example,
The follow python code:
def multiples_of_2():
i = 0
while True:
i = i + 2
yield i
How do we translate thi
As Will mentioned, languages like python do the job of storing the state of the stack between successive calls of the generator. Since C does not have this mechanism, you'll have to do it yourself. The "generic" way of doing this is not for the faint-hearted, as Greg pointed out. The traditional C way of doing this would be for you to define and maintain the state yourself and pass it in and out of your method. So:
struct multiples_of_two_state {
int i;
/* all the state you need should go in here */
};
void multiples_of_two_init(struct multiples_of_two_state *s) {
s->i = 0;
}
int multiples_of_two_next(struct multiples_of_two_state *s) {
s->i += 2;
return s->i;
}
/* Usage */
struct multiples_of_two_state s;
int result;
multiples_of_two_init(&s);
for (int i=0; i