举个例子,
以下python代码:
def multiples_of_2():
i = 0
while True:
i = i + 2
yield i
Run Code Online (Sandbox Code Playgroud)
我们如何将其转换为C代码?
编辑:我希望将此python代码转换为C语言中的类似生成器,并使用next()函数.我不想要的是如何在C中创建一个函数来输出2的倍数.2的倍数仅仅是一个例子来说明C中的惰性eval生成器的问题.
jdb*_*jdb 20
您可以尝试将其封装在struct:
typedef struct s_generator {
int current;
int (*func)(int);
} generator;
int next(generator* gen) {
int result = gen->current;
gen->current = (gen->func)(gen->current);
return result;
}
Run Code Online (Sandbox Code Playgroud)
然后你定义你的倍数:
int next_multiple(int current) { return 2 + current; }
generator multiples_of_2 = {0, next_multiple};
Run Code Online (Sandbox Code Playgroud)
你通过电话获得下一个倍数
next(&multiples_of_2);
Run Code Online (Sandbox Code Playgroud)