Inline Functions, Variadic, Compound Literals
static inline as a type-safe macro replacement, va_list/va_start/va_arg, compound literals, designated initializers.
Four pieces, each solving a different limitation of plain functions or plain macros.
static inline
static inline int max(int a, int b) {
return a > b ? a : b;
}This is the fix for the double-evaluation problem macros have (see 1.6.F) — a real function only evaluates its arguments once, and static inline asks the compiler to paste the body directly at each call site when it can, getting macro-like speed without losing type checking or single evaluation.
Variadic functions
#include <stdarg.h>
int sum(int count, ...) {
va_list args;
va_start(args, count);
int total = 0;
for (int i = 0; i < count; i++) {
total += va_arg(args, int);
}
va_end(args);
return total;
}
sum(3, 10, 20, 30); /* 60 */This is exactly how printf itself takes a variable number of arguments — va_start anchors onto the last named parameter, va_arg pulls one argument at a time by an explicitly given type (there's no way to ask it for "whatever type is next," the caller has to already know), and va_end cleans up.
Compound literals and designated initializers
struct point p = (struct point){.x = 1, .y = 2}; /* an unnamed struct value, usable inline */
int lookup[10] = {[2] = 20, [5] = 50}; /* only indices 2 and 5 set; rest default to 0 */A compound literal builds a struct value on the spot without needing a named variable first — useful for passing a one-off struct straight into a function call. Designated initializers in an array work the same way structs do, setting specific indices by position instead of relying on order.
Notes from readers
Comments — via GitHub