typestar

Callbacks with context in C

The C convention for a callback: the function pointer plus a void pointer of your own.

typedef void (*Visitor)(int value, void *user);

void each(const int *values, size_t n, Visitor visit, void *user) {
    for (size_t i = 0; i < n; i++) {
        visit(values[i], user);
    }
}

static void accumulate(int value, void *user) {
    long *total = user;
    *total += value;
}

long sum_via_callback(const int *values, size_t n) {
    long total = 0;
    each(values, n, accumulate, &total);
    return total;
}

How it works

  1. The void *user argument carries whatever the caller needs.
  2. The library never inspects it, only hands it back.
  3. This is how qsort_r, threads and event loops all look.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
388
Tokens
120
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 76 seconds.

Type this snippet

Step 3 of 4 in Generic & function pointers, step 8 of 25 in Pointers & memory.

← Previous Next →