c / expert
Snippet
Compile-Time Polymorphism via C11 Type-Generic Expressions
C11 introduced the _Generic keyword, enabling type-based compile-time macro dispatch without runtime overhead or name mangling. The compiler evaluates the static type of the controlling expression and selects the corresponding function pointer or macro replacement, giving C function overloading capabilities while preserving strict static typing.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>#include <math.h>#define print_val(X) _Generic((X), \int: print_int, \double: print_double, \default: print_unknown \)(X)void print_int(int x) { printf("Integer: %d\n", x); }void print_double(double x) { printf("Double: %.2f\n", x); }void print_unknown(void *x) { (void)x; printf("Unknown type\n"); }int main(void) {int i = 42;double d = 3.14159;print_val(i);print_val(d);return 0;}
Breakdown
1
#define print_val(X) _Generic((X), \
Defines a type-generic macro that initiates type inspection on the argument X.
2
int: print_int, \
Maps integer arguments at compile time directly to the print_int implementation.
3
double: print_double, \
Maps double-precision floating-point arguments to the print_double implementation.
4
default: print_unknown \
Provides a fallback resolution path for any types not explicitly specified in the generic association list.
5
)(X)
Immediately invokes the selected function pointer with the original argument X.