模仿上一篇文,用 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 或更新的版本都有支援。