我对宏扩展延迟有疑问。这是一个例子:
#include <stdio.h>
#define CONST_ABC 15
#define CONST_5 7
#define ABC 5
#define PRINT(x) printf("CONST=%d\n", CONST_ ## x)
// The problematic macro
#define PRINT2(x) PRINT(x)
int main(int argc, char *argv[])
{
PRINT(ABC); // Prints 15 - OK
PRINT2(ABC); // Prints 7 - Not OK.
}
如何定义
PRINT2
宏,以便它将使用PRINT
,结果将为15?我越来越:CONST=15
CONST=7
并希望获得:
CONST=15
CONST=15
最佳答案
由于C99允许使用空的宏参数,因此它至少需要C99编译器。但是,即使在C89模式下,某些编译器也可能允许它们作为扩展。这是代码:
#include <stdio.h>
#define CONST_ABC 15
#define CONST_5 7
#define ABC 5
#define PRINT(x) printf("CONST=%d\n", CONST_ ## x)
// The problematic macro
#define PRINT2(x, y) PRINT(x ## y)
int main(int argc, char *argv[])
{
PRINT(ABC); // Prints 15 - OK
PRINT2(ABC,); // Prints 7 - Not OK.
}
第二个参数(即
y
)为空,使其成为空的预处理 token 。 ##
运算符可防止参数扩展,因此串联的结果与x
参数相同。C11 6.10.3.1/p1参数替换(强调我的意思):
在调用类似函数的宏的参数之后
确定后,将进行参数替换。中的参数
替换列表,除非前面带有
#
或##
预处理 token 或后跟一个
##
预处理 token (请参见下文),由包含在其中的所有宏之后的相应参数
扩展。在替换之前,每个参数的预处理
标记完全被宏替换,就好像它们构成了其余的
预处理文件;没有其他预处理 token 可用。