Type-generic printing macro
suggest change#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(const char *x) { (void)x; 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");
}
int: 42
double: 3.14
unknown argument
_Generic is a C11 feature. The controlling expression is not evaluated. Its type is taken after lvalue conversion, array-to-pointer conversion, and function-to-pointer conversion, so a string literal matches as char * and selects default. A float does not match double. No diagnostic is required for the default association. Add an association when that type should be printed differently.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents