Re: [问题] printf type of value

楼主: lantw44 (#######################)   2014-07-30 20:23:37
模仿上一篇文,用 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 或更新的版本都有支援。
作者: carylorrk (carylorrk)   2014-07-30 20:51:00
C11...完全没有在跟 普遍度好像比 C++11 低很多
作者: firejox (Tangent)   2014-07-30 22:09:00
long long的问题 用typedef绕圈子不就解决了?
楼主: lantw44 (#######################)   2014-07-31 23:55:00
只是想说用 _Generic 可能看起来比较直接一点

Links booklink

Contact Us: admin [ a t ] ucptt.com