加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – __typeof变量和printf

发布时间:2020-12-16 09:53:51 所属栏目:百科 来源:网络整理
导读:如果我使用__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,
如果我使用__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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读