c - __typeof 变量和 printf

标签 c gcc printf

如果我定义一个通用宏,使用 __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/

相关文章:

c - 尽管引用了未声明的函数(在 header 中或其他地方),是什么让我的编译器编译代码?

linux - 使用 g++ 在 Linux 上使用 Valgrind 拦截全局函数

c - 带有 Quartz 的 GTK 窗口 [从 GStreamer 的问题开始]

c - 如何在 GCC 插件中添加内置函数?

formatting - 如何在 Smalltalk/Pharo 中打印固定字符数的数字

c - 如何打印在 C 函数 main 中初始化的二维数组?

C:预期输出

c - 句子之间有两个空格

c - 请求非结构或 union 中的成员 'isr_status'

c - 使用 g_hash_table_new_full 丢失信息