3.24 ジェネレータ
Python の関数で return の代わりに yield を使うと、その関数を呼び出すごとに「次の値」を返す。このような関数を「ジェネレータ」と言う。
C 言語には yield のようなキーワードはないが、ジェネレータのような機能は実現できる。以下に例を示す。
(注意) この例で関数内で static な変数を使用しているが、そのような関数は「再入不可」であることに注意が必要である。
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
/* ジェネレータ関数 */
int32_t genint(bool, bool*);
/* main */
void main() {
bool last;
int32_t n = genint(true, &last);
while (! last) {
printf("%d\n", n);
n = genint(false, &last);
}
puts("Done.");
}
/* 整数を返すジェネレータ関数 (再入不可) */
int32_t genint(bool reset, bool* last) {
static int32_t data[] = {5, 8, 1, 6};
static int current;
if (reset)
current = 0;
*last = (bool)(current >= 4);
int32_t n = data[current];
current++;
return n;
}
実行例
$ ./bin/yield 5 8 1 6 Done. $