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
- A
staticfunction cannot be called from another file. - That keeps the public surface small and the names free.
- The linker never even sees the symbol.
Keywords and builtins used here
charconstcount_ifcount_vowelsforifintis_vowelreturnsize_tstatic
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.
Step 3 of 3 in Encapsulation, step 7 of 11 in APIs, errors & testing.