#include <stdio.h>
void print_int(int x) { printf("int: %d\n", x); }
void print_dbl(double x) { printf("double: %g\n", x); }
void print_default() { puts("unknown argument"); }
#define print(X) _Generic((X), \
int: print_int, \
double: print_dbl, \
default: print_default)(X)
int main(void) {
print(42);
print(3.14);
print("hello, world");
}
Output:
int: 42
double: 3.14
unknown argument
Note that if the type is neither int
nor double
, a warning would be generated. To eliminate the warning, you can add that type to the print(X)
macro.