c / expert
Snippet
Type-Generic Selection with _Generic
Introduced in C11, _Generic provides a way to write type-generic macros. It acts like a compile-time switch statement that selects an expression based on the type of a controlling expression, allowing for polymorphism without runtime overhead.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>#define print_val(x) _Generic((x), \int: "Integer: %d\n", \double: "Double: %f\n", \char*: "String: %s\n", \default: "Unknown type\n")int main() {int i = 10;double d = 3.14;printf(print_val(i), i);printf(print_val(d), d);return 0;}
Breakdown
1
#define print_val(x) _Generic((x), ...)
Defines a macro that uses the controlling expression 'x' to select a result string.
2
int: "Integer: %d\n",
If 'x' is of type int, this specific format string is selected at compile time.
3
default: "Unknown type\n"
Provides a fallback case if the type of 'x' does not match any specified types.