gpt4 book ai didi

c - 宏扩展的奇怪结果

转载 作者:太空狗 更新时间:2023-10-29 15:46:39 27 4
gpt4 key购买 nike

考虑以下代码片段

#include<stdio.h>
#define A -B
#define B -C
#define C 5

int main()
{
printf("The value of A is %d\n", A);
return 0;
}

输出

The value of A is 5

但这根本不应该编译,因为展开后它应该看起来像 printf("The value of A is %d\n", --5); 然后它应该给出编译错误说 lvalue 需要。不是吗?

最佳答案

将 -E 选项传递给它(例如:gcc -E a.c)。这将输出预处理的源代码。

int main()
{
printf("The value of A is %d\n", - -5);
return 0;
}

所以它会在 --5 之间引入一个空格,因此它不会被视为递减运算符 --,所以 printf 将打印 5.

GCC 文档 Token Spacing提供有关为什么会产生额外空间的信息:

First, consider an issue that only concerns the stand-alone preprocessor: there needs to be a guarantee that re-reading its preprocessed output results in an identical token stream. Without taking special measures, this might not be the case because of macro substitution. For example:

 #define PLUS +
#define EMPTY
#define f(x) =x=
+PLUS -EMPTY- PLUS+ f(=)
==> + + - - + + = = =
not
==> ++ -- ++ ===

One solution would be to simply insert a space between all adjacent tokens. However, we would like to keep space insertion to a minimum, both for aesthetic reasons and because it causes problems for people who still try to abuse the preprocessor for things like Fortran source and Makefiles.

For now, just notice that when tokens are added (or removed, as shown by the EMPTY example) from the original lexed token stream, we need to check for accidental token pasting. We call this paste avoidance. Token addition and removal can only occur because of macro expansion, but accidental pasting can occur in many places: both before and after each macro replacement, each argument replacement, and additionally each token created by the # and ## operators.

关于c - 宏扩展的奇怪结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41857361/

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