模仿上一篇文,用 macro 来做,但是改用 C11 的 _Generic,
这样也能解决 long long 的问题。
#include <stdio.h>
#define FORMAT(x) \
_Generic((x), \
int: "type = int, data = %d\n", \
char: "type = char, data = %c\n", \
long: "type = long, data = %ld\n", \
float: "type = float, data = %f\n", \
long long: "type = long long, data = %lld\n" )
int main () {
int a = 0;
char b = 'a';
long c = 100;
float d = 5.4;
long long e = 12345678901234LL;
printf (FORMAT (a), a);
printf (FORMAT (b), b);
printf (FORMAT (c), c);
printf (FORMAT (d), d);
printf (FORMAT (e), e);
return 0;
}
不过也因为是 C11 新支援的语法,所以要用比较新的编译器才行,
测试过 GCC 4.9 和 Clang 3.1 或更新的版本都有支援。