typestar

Keeping helpers private in C

static at file scope hides a function from every other translation unit.

#include <stddef.h>

static int is_vowel(char c) {
    return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}

static size_t count_if(const char *text, int (*test)(char)) {
    size_t n = 0;
    for (; *text; text++) {
        if (test(*text)) {
            n++;
        }
    }
    return n;
}

size_t count_vowels(const char *text) {
    return count_if(text, is_vowel);
}

How it works

  1. A static function cannot be called from another file.
  2. That keeps the public surface small and the names free.
  3. The linker never even sees the symbol.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
334
Tokens
124
Three-star pace
105 tpm

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

Type this snippet

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

← Previous Next →