zoukankan      html  css  js  c++  java
  • 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都会展开。

  • 相关阅读:
    增加文章
    网站之注册
    C#常用的引用
    Session.Abandon和Session.Clear有何不同 (转)
    C#文件路径的写法
    UpdatePanel的用法详解
    [转]asp:ScriptManager
    Git 常用命令
    AJAX请求 $.post方法的使用
    a 标签中调用js的几种方法
  • 原文地址:https://www.cnblogs.com/jaletech/p/the-expanding-problem-in-c.html
Copyright © 2011-2022 走看看