Generic Macro in C

Level 5357 keystrokes

Defines PRINT_TYPE with C11 _Generic, which picks a string at compile time from the type of its argument. Applied to an int, a float, a double and a char *, it prints 10 is int, 3.140000 is float, 2.718000 is double and hello is string.

C code

// C11 _Generic picks a branch by the type of x at compile time
// int, float and double give their names, char * gives "string", any other type "unknown"
1#define PRINT_TYPE(x) _Generic((x), \
2 int: "int", \
3 float: "float", \
4 double: "double", \
5 char *: "string", \
6 default: "unknown")
7
// One variable of each type to test
8int a = 10;
// The f suffix makes 3.14f a float, not a double
9float b = 3.14f;
10double c = 2.718;
11char *s = "hello";
12
// Each call selects its string at compile time: prints 10 is int
13printf("%d is %s\n", a, PRINT_TYPE(a));
// %f prints 6 decimals: 3.140000 is float
14printf("%f is %s\n", b, PRINT_TYPE(b));
// Prints 2.718000 is double
15printf("%f is %s\n", c, PRINT_TYPE(c));
// The char * branch matches s: prints hello is string
16printf("%s is %s\n", s, PRINT_TYPE(s));

Output

10 is int
3.140000 is float
2.718000 is double
hello is string
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • "× 20
  • ,× 13
  • (× 11
  • )× 11
  • \× 9
  • ;× 8
  • %× 8
  • _× 6
  • :× 5
  • =× 4

More C examples at level 5

← C typing practice