c / intermediate
Snippet
Type-Generic Selection with _Generic
Introduced in C11, '_Generic' provides a way to select an expression at compile-time based on the type of a controlling expression, enabling basic generic programming.
snippet.c
1
2
3
4
5
6
7
#define typename(x) _Generic((x), \int: "int", \float: "float", \char *: "string", \default: "other")const char *type = typename(3.14f);
Breakdown
1
_Generic((x),
Begins the type-based selection based on the variable 'x'.
2
float: "float",
If 'x' is a float, the expression evaluates to the string literal "float".