c / intermediate
Snippet
Type-Generic Selection with _Generic
The '_Generic' keyword, introduced in C11, provides a way to perform compile-time type dispatch. It allows a macro to evaluate to different expressions based on the type of its controlling expression, enabling a form of polymorphism in plain C.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>#define print_type(x) _Generic((x), \int: "integer", \float: "float", \char*: "string", \default: "unknown")int main() {int a = 5;float b = 2.5f;char* c = "hello";printf("a is %s\n", print_type(a));printf("b is %s\n", print_type(b));printf("c is %s\n", print_type(c));return 0;}
Breakdown
1
_Generic((x), ...)
Starts the generic selection based on the type of the expression 'x'.
2
int: "integer"
Specifies that if 'x' is of type 'int', the result of the expression is "integer".
3
default: "unknown"
Provides a fallback result if the type of 'x' does not match any specified cases.