如果我使用__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; })
可能吗?
答案 0 :(得分:3)
您可以使用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)
答案 1 :(得分:2)
#include <stdio.h>
#define FMT(_pre_, x, _post_) _Generic((x), \
char: _pre_ "%c" _post_, \
int: _pre_ "%d" _post_, \
long: _pre_ "%ld" _post_)
int main()
{
int x = 42;
long y = 432144312432321;
printf(FMT("foo: ", x, "\n"), x);
printf(FMT("bar: ", y, "\n"), y);
return 0;
}
前后的东西有点难看,但我还没有找到更好的方法。我们不能依赖C预处理器中的字符串连接,因为编译器会对_Generic
进行评估,为时已晚。
答案 2 :(得分:2)
例如,使用C11 _Generic
(必须完成以完成检查):
#define DEBUG_INT(a, b) DEBUG("%d %d?", (a), (b))
#define DEBUG_DOUBLE(a, b) DEBUG("%f %f?", (a), (b))
#define FAIL(a, b) assert(0)
#define max(a,b) \
({ typeof (a) _a = (a); \
typeof (b) _b = (b); \
_Generic((_a), int: DEBUG_INT, double: DEBUG_DOUBLE, default: FAIL))(_a, _b); \
_a > _b ? _a : _b; })
或使用__builtin_types_compatible_p
gcc扩展程序:
#define max(a,b) \
({ typeof (a) _a = (a); \
typeof (b) _b = (b); \
if (__builtin_types_compatible_p(typeof(int), _a) && __builtin_types_compatible_p(typeof(int), _a)) DEBUG_INT(_a, _b); \
else if (__builtin_types_compatible_p(typeof(double), _a) && __builtin_types_compatible_p(typeof(double), _a)) DEBUG_DOUBLE(_a, _b); \
else FAIL(_a, _b);
_a > _b ? _a : _b; })