我无法理解为什么以下代码打印2而不是1 ...
#include <stdio.h>
#define ABS(x) ((x) < 0) ? -(x) : (x)
int main()
{
printf("%d", ABS(ABS(-2)-(ABS(-3))));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个问题在我们的考试中,我回答输出是1但是在编译之后我得到2 ...有人请解释实际表达的内容...提前谢谢.
括号有问题。如果扩展宏,您将得到一个复杂的嵌套三元运算,其计算结果为2(请参阅更新中的扩展)。为了获得理想的结果,请用括号将宏括起来。
更新:手动扩展:
ABS(ABS(-2)-(ABS(-3)))
Run Code Online (Sandbox Code Playgroud)
扩展到:
((ABS(-2)-(ABS(-3))) < 0) ? -(ABS(-2)-(ABS(-3))) : (ABS(-2)-(ABS(-3)))
Run Code Online (Sandbox Code Playgroud)
ABS(-3)到处都被括号包围,因此它被安全地评估为3,因此无需扩展它。所以我们最终得到:
(( ((-2) < 0) ? -(-2) : (-2) - 3) < 0) ? -(ABS(-2)-3) : (ABS(-2)-3)
Run Code Online (Sandbox Code Playgroud)
(ABS(-2)-3)将扩展到
((-2) < 0) ? -(-2) : (-2) - 3 = 2
Run Code Online (Sandbox Code Playgroud)
评估整体:
(( true ? 2 : -5 < 0) ? -2 : 2
或
(2 < 0) ? -2 : 2 = 2
这是观察到的结果,希望它是可遵循的。
这是埃诺