static inline in headers in C
A small function in a header must be static inline, or every including file collides.
#include <stddef.h>
static inline int clamp(int value, int low, int high) {
if (value < low) {
return low;
}
if (value > high) {
return high;
}
return value;
}
static inline size_t min_size(size_t a, size_t b) {
return (a < b) ? a : b;
}
int clamped_sum(int a, int b) {
return clamp(a, 0, 100) + clamp(b, 0, 100);
}
How it works
staticgives each translation unit its own copy.inlineinvites the compiler to expand it in place.- This is the type-safe alternative to a function-like macro.
Keywords and builtins used here
clampclamped_sumifinlineintmin_sizereturnsize_tstatic
The run, in numbers
- Lines
- 19
- Characters to type
- 318
- Tokens
- 98
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 62 seconds.
Step 4 of 4 in Macros, step 4 of 12 in Preprocessor & headers.