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
- A reader takes
const T *and promises not to write. - A writer takes
T *and says so in the type. - The compiler enforces the promise, so it is real documentation.
Keywords and builtins used here
constdoubleforifintlongreturnseries_meanseries_pushsize_tstructtypedef
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.
Step 4 of 4 in Signatures, step 4 of 11 in APIs, errors & testing.