gpt4 book ai didi

c - 停止宏扩展

转载 作者:行者123 更新时间:2023-12-01 23:14:47 24 4
gpt4 key购买 nike

我有宏扩展延迟的问题。下面是一个例子:

#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 )为空,使其成为空的预处理标记。 ##运算符防止参数扩展,因此连接的结果与 x 相同争论。

C11 6.10.3.1/p1 参数替换(强调我的):

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. Before being substituted, each argument’s preprocessing tokens are completely macro replaced as if they formed the rest of the preprocessing file; no other preprocessing tokens are available.

关于c - 停止宏扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28547085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com