开发者

Preprocessor Quoting macro arguments

Suppose I have some macro #define NAME name, and I want to define some other macro which will expand to the quoted value. That is, as if I had also defined #define NAME_STR "name". Is there a neater way than the following?

#define QUOT(str)   #str
#define QUOT_ARG(str)   QUOT(str)
#define NAME_STR    开发者_Go百科QUOT_ARG(NAME)


Not really, due to the fact that macro arguments are not expanded when used in stringification. From the GNU C PreProcessor manual:

Unlike normal parameter replacement, the argument is not macro-expanded first. This is called stringification.

From the same source:

If you want to stringify the result of expansion of a macro argument, you have to use two levels of macros.

...which continues with an example:

 #define xstr(s) str(s)
 #define str(s) #s
 #define foo 4
 str (foo)
      ==> "foo"
 xstr (foo)
      ==> xstr (4)
      ==> str (4)
      ==> "4"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜