c / expert
Snippet
Type-Generic Macro Selection via C11 _Generic Keyword
Introduced in C11, the _Generic keyword evaluates the compile-time type of an controlling expression and selects a corresponding association expression. When wrapped in a preprocessor macro, _Generic enables function overloading in C based strictly on argument types without incurring runtime function-dispatch overhead.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>void print_int(int val) { printf("Integer: %d\n", val); }void print_double(double val) { printf("Double: %.2f\n", val); }void print_unknown(void *val) { (void)val; printf("Unknown type\n"); }#define print_value(X) _Generic((X), \int: print_int, \double: print_double, \default: print_unknown \)(X)int main(void) {print_value(42);print_value(3.14);return 0;}
Breakdown
1
#define print_value(X) _Generic((X), \
Begins C11 type-generic selector macro matching the static type of expression X.
2
int: print_int, \
Associates integer type with print_int function pointer target.
3
default: print_unknown \
Defines fallback association when X matches no explicit listed type.