c语言中的宏求值 [英] Macros evaluation in c programming language

查看:25
本文介绍了c语言中的宏求值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
什么是“#define STR(a)#a”怎么办?

#include <stdio.h>
  #define f(a,b) printf("yes")
  #define g(a)   #a
  #define h(a) g(a)

  int main()
  {
        printf("%s
",h(f(1,2)));
        printf("%s
",g(f(1,2)));

  }

谁能解释一下为什么两个 printf() 语句的输出不同.

Can somebody explain why output is different for both printf() statements.

推荐答案

由于预处理器执行操作的顺序不同,输出不同,这在 C99 标准中的第 6.10.3 节(以及以下)中进行了描述.特别是6.10.3.1/1中的这句话:

The output is different because of the order in which the preprocessor does things, which is described in section 6.10.3 (and those following) in the C99 standard. In particular, this sentence from 6.10.3.1/1:

替换列表中的参数,除非前面有 ### 预处理标记或后跟 ## 预处理标记,在其中包含的所有宏都已展开后,由相应的参数替换.

A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token, is replaced by the corresponding argument after all macros contained therein have been expanded.

所以在第一行中,当扩展h的调用时,参数f(1,2)被扩展之前它替换h 的参数 a.# 仅在稍后在重新扫描所有输出时看到对 g 的结果调用时才起作用.

So in the first line, when expanding the invocation of h, the argument f(1,2) is expanded before it replaces h's parameter a. The # only comes into play later when the resulting invocation of g is seen when the output of all that is rescanned.

但是在第二行,立即看到 # 并且上面引用的除非前面有..."子句触发了不同的行为.

But on the second line, the # is seen immediately and the "unless preceded by..." clause of the quotation above triggers the different behaviour.

另请参阅相关的 C-FAQ 条目.

这篇关于c语言中的宏求值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆