c / expert
Snippet
Type-Generic Selection with _Generic
Introduced in C11, the _Generic keyword allows for compile-time type-based selection. It is often used in macros to provide a form of polymorphism or function overloading. The preprocessor selects the appropriate function or expression based on the type of the first argument provided to _Generic.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#define print(x) _Generic((x), \int: print_int, \double: print_double, \char*: print_string, \default: print_unknown \)(x)void print_int(int i) { printf("Int: %d\n", i); }void print_double(double d) { printf("Double: %f\n", d); }int main() {print(42); // Calls print_intprint(3.14); // Calls print_double}
Breakdown
1
_Generic((x),
The keyword initiating the selection based on the expression 'x'.
2
int: print_int,
If 'x' is of type int, this branch evaluates to the function pointer 'print_int'.
3
)(x)
The selected function pointer is immediately invoked with the argument 'x'.