#和##中的宏 [英] # and ## in macros

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

问题描述

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

  int main()
  {
          printf("%s\n",h(f(1,2)));
          printf("%s\n",g(f(1,2)));
          return 0;
  }

只是通过查看程序的一个可能希望输出是,同为两个printf的语句。但在运行程序你得到它的:

Just by looking at the program one "might" expect the output to be, the same for both the printf statements. But on running the program you get it as:

bash$ ./a.out
12
f(1,2)
bash$

为什么会这样呢?

Why is it so?

推荐答案

由于那该是多么preprocessor的作品。

Because that is how the preprocessor works.

一个单独的'#'将从给定的参数创建一个字符串,而不管这样的说法包含,而双##将通过连接参数创建一个新的令牌。

A single '#' will create a string from the given argument, regardless of what that argument contains, while the double '##' will create a new token by concatenating the arguments.

尝试寻找在preprocessed输出(例如用的gcc -E ),如果你想更好地了解宏如何评估。

Try looking at the preprocessed output (for instance with gcc -E) if you want to understand better how the macros are evaluated.

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

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