到底是如何做双stringize招工作的? [英] How, exactly, does the double-stringize trick work?

查看:121
本文介绍了到底是如何做双stringize招工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前至少有一些的 C preprocessors让你stringize宏的价值,而不是它的名称,将其通过一个功能类似宏另一个stringizes它:

At least some C preprocessors let you stringize the value of a macro, rather than its name, by passing it through one function-like macro to another that stringizes it:

#define STR1(x) #x
#define STR2(x) STR1(x)
#define THE_ANSWER 42
#define THE_ANSWER_STR STR2(THE_ANSWER) /* "42" */

使用范例这里

这不工作,至少在海湾合作委员会锵(均与 -std = C99 ),但我不知道的如何的它工作在C-标准的条款。

This does work, at least in GCC and Clang (both with -std=c99), but I'm not sure how it works in C-standard terms.

这是由行为C99保证?结果
如果是这样,如何​​保证C99呢?结果
如果不是,在什么时候的行为从根本C-定义为GCC定义的?

Is this behavior guaranteed by C99?
If so, how does C99 guarantee it?
If not, at what point does the behavior go from C-defined to GCC-defined?

推荐答案

是的,它保证。

它的工作原理,因为参数宏本身是宏展开,的除了的在宏参数名出现在宏体与stringifier#或令牌贴纸##。

It works because arguments to macros are themselves macro-expanded, except where the macro argument name appears in the macro body with the stringifier # or the token-paster ##.

6.10.3.1/1:

6.10.3.1/1:

...参数为后
  一个函数宏调用的
  已经确定,论证
  取代发生。一个参数
  在替换列表,除非
  $ P $由#pceded或## preprocessing
  令牌或后跟一个##
  preprocessing令牌(见下文),是
  通过相应的参数替换
  其中所含的所有宏后
  已扩大...

... 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...

所以,如果你做的 STR1(THE_ANSWER)那么你得到THE_ANSWER,因为STR1的参数不是宏扩展。然而,STR2的参数的的宏展开时,它的代入STR2的定义,因此这给STR1的 42 ,用参数的42的结果。

So, if you do STR1(THE_ANSWER) then you get "THE_ANSWER", because the argument of STR1 is not macro-expanded. However, the argument of STR2 is macro-expanded when it's substituted into the definition of STR2, which therefore gives STR1 an argument of 42, with the result of "42".

这篇关于到底是如何做双stringize招工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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