typestar

Opaque handles in C

The header declares an incomplete type, so callers cannot see the fields.

#include <stdlib.h>

typedef struct Counter Counter;

struct Counter {
    long value;
    long limit;
};

Counter *counter_new(long limit) {
    Counter *c = malloc(sizeof *c);
    if (c != NULL) {
        c->value = 0;
        c->limit = limit;
    }
    return c;
}

int counter_bump(Counter *c) {
    if (c->value >= c->limit) {
        return 0;
    }
    c->value++;
    return 1;
}

void counter_free(Counter *c) {
    free(c);
}

How it works

  1. A forward-declared struct is an opaque type.
  2. Only the implementation file has the definition.
  3. Every operation goes through functions, so layout stays private.

Keywords and builtins used here

The run, in numbers

Lines
29
Characters to type
368
Tokens
116
Three-star pace
105 tpm

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

Type this snippet

Step 1 of 3 in Encapsulation, step 5 of 11 in APIs, errors & testing.

← Previous Next →