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都会展开。

posted @ 2014-12-09 16:48  野风鼓瑟震山岗  阅读(207)  评论(0编辑  收藏  举报