Skip to main content

Practice ยท 3 of 4

Context-Carrying Callbacks

Implement the for_each with context โ€” the closure pattern: ``c typedef struct { long long total; size_t count; } StatsCtx; /* in boilerplate */ /* calls visit(i, ctx) for each i in [0, n) in order */ void for_each_i(size_t n, void (*visit)(size_t i, void *ctx), void *ctx); /* convenience: uses for_each_i with a visitor that adds i to ctx->total and increments ctx->count */ void stats_collect(size_t n, StatsCtx *ctx); ``

Difficulty: intermediate

Back to lesson: Practice: Dispatch & Context Gym