CKTIS / C
iterators and generators — concept C23
C defines neither generators nor an iterator protocol, so iteration is modeled with pointer-and-end pairs or a cursor structure and `next` function. The contract must distinguish end from failure, keep the collection alive for the traversal, and forbid dereferencing an end cursor.
Version: C23
Syntax
iterators and generatorsC defines neither generators nor an iterator protocol, so iteration is modeled with pointer-and-end pairs or a cursor structure and next function. The contract must distinguish end from failure, keep the collection alive for the traversal, and forbid dereferencing an end cursor.
For a custom collection, define a struct Cursor with current and end pointers plus a next(cursor, out) function returning a distinct end status. Client code then need not know the collection layout, and one traversal has explicit state.
A cursor becomes invalid after the collection is reallocated or released; two cursors may also need independent state. For an empty range begin == end and no element may be read, while a source failure must differ from ordinary end of sequence.
Examples
#include <stdio.h>
struct Cursor { const int *next; const int *end; };
static int take(struct Cursor *cursor, int *out) { if (cursor->next == cursor->end) return 0; *out = *cursor->next++; return 1; }
int main(void) { int data[] = {4, 5}; struct Cursor c = {data, data + 2}; int value, sum = 0; while (take(&c, &value)) sum += value; printf("%d\n", sum); return 0; }
Result
9
C defines neither generators nor an iterator protocol, so iteration is modeled with pointer-and-end pairs or a cursor structure and `next` function. The contract must distinguish end from failure, keep the collection alive for the traversal, and forbid dereferencing an end cursor.