typestar

Reading versus writing APIs in C

const in the signature says whether a function will change what you hand it.

typedef struct {
    int values[8];
    size_t count;
} Series;

double series_mean(const Series *s) {
    long total = 0;
    for (size_t i = 0; i < s->count; i++) {
        total += s->values[i];
    }
    return s->count ? (double) total / (double) s->count : 0.0;
}

int series_push(Series *s, int value) {
    if (s->count >= 8) {
        return 0;
    }
    s->values[s->count++] = value;
    return 1;
}

How it works

  1. A reader takes const T * and promises not to write.
  2. A writer takes T * and says so in the type.
  3. The compiler enforces the promise, so it is real documentation.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
354
Tokens
127
Three-star pace
100 tpm

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

Type this snippet

Step 4 of 4 in Signatures, step 4 of 11 in APIs, errors & testing.

← Previous Next →