• C中宏展开问题


    C中宏展开问题

    简单记录一下碰到的问题。

    #define STR(x) #x
    

    我们知道使用上面的宏可以将x转换为字符串"x"。
    但是如果这样用:

    #define NUM 3
    #define STR(x) #x
    STR(NUM) --> 实际输出为:"NUM".
    

    这是为啥呢?C99标准中有一段话:

    ... After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded...

    简单解释一下这段话的意思。在C中类函数的宏定义会在“调用”的时候将其能展开的全部展开,除非(unless)宏定义中出现#或##.也即,上面的STR(x)中的x是不会展开的。为了使其展开,必须添加一个助手宏。
    解决方法:

    #define NUM 3
    #define STR(x) #x
    #define XSTR(x) STR(x)  //添加一个助手宏
    
    XSTR(NUM) --> 实际输出为:"3".
    

    添加一个助手宏XSTR(x),在XSTR(x)宏中就不存在#或者##了,因此STR和x都会展开。

  • 相关阅读:
    SharePoint中获取当前登录的用户名
    SharePoint 2013 图文开发系列之InfoPath入门
    在InfoPath中如何获取当前用户的信息(Profile)
    更新当前列并添加其他列
    poj3067 Japan
    poj2481 Cows
    poj1195 Mobile phones
    poj2299 Ultra-QuickSort
    lower_bound()和upper_bound
    hdu4339 Query
  • 原文地址:https://www.cnblogs.com/jaletech/p/the-expanding-problem-in-c.html
Copyright © 2020-2023  润新知