如果我定义一个通用宏,使用 __typeof__
/typeof
,有没有办法同时选择一个 printf
转换说明符,以一种通用的方式?
我的意思是,例如:
#define max(a,b) \
({ typeof (a) _a = (a); \
typeof (b) _b = (b); \
DEBUG(( "%" __PRI_TYPE_PREFIX(a) > "%" __PRI_TYPE_PREFIX(b) "?", _a, _b)) \ <-- hypothetical
_a > _b ? _a : _b; })
有可能吗?
最佳答案
您可以使用 C11 的 _Generic
功能来执行此操作,例如
#define printf_dec_format(x) _Generic((x), \
char: "%c", \
signed char: "%hhd", \
unsigned char: "%hhu", \
signed short: "%hd", \
unsigned short: "%hu", \
signed int: "%d", \
unsigned int: "%u", \
long int: "%ld", \
unsigned long int: "%lu", \
long long int: "%lld", \
unsigned long long int: "%llu", \
float: "%f", \
double: "%f", \
long double: "%Lf", \
char *: "%s", \
void *: "%p")
#define print(x) printf(printf_dec_format(x), x)
(示例取自:Rob's Programming Blog)
关于c - __typeof 变量和 printf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25445014/