这段 C 代码中的括号如何使结果如此不同?
这段代码的输出:
#define RECIPROCAL_1(x) 1/(x)
#define RECIPROCAL_2(x) 1/x
main()
{
float x=8.0, y;
y = RECIPROCAL_1(x+10.0);
printf("1/%3.1f = %8.5f\n", x, y);
y = RECIPROCAL_2(x+10.0);
printf("1/%3.1f = %8.5f\n", x, y);
}
是输出=
1/8.0 = 0.05556
1/8.0 = 10.12500
我看不出它是如何工作的。我很感激任何提示。
The output for this code:
#define RECIPROCAL_1(x) 1/(x)
#define RECIPROCAL_2(x) 1/x
main()
{
float x=8.0, y;
y = RECIPROCAL_1(x+10.0);
printf("1/%3.1f = %8.5f\n", x, y);
y = RECIPROCAL_2(x+10.0);
printf("1/%3.1f = %8.5f\n", x, y);
}
is output =
1/8.0 = 0.05556
1/8.0 = 10.12500
I can't see how this works though. I appreciate any tips .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
宏替换的扩展如下:
becomes
和
becomes
因为
/
的优先级高于+
,所以y
的值不同。这是一个很好的例子,说明了为什么挑剔的程序员在没有其他解决方案可行的情况下只使用宏。即便如此,那些觉得有必要使用宏的挑剔的程序员总是会使用足够的括号来确保避免此类陷阱。
The macro substitutions are expanded like this:
becomes
and
becomes
Because
/
has a higher precedence that+
the values fory
are different.This is an excellent example of why the discerning programmer only reaches for macros when no other solution is viable. And even then, those discerning programmers that feel compelled to use macros, will always use sufficient parenthesise as to make sure such pitfalls are avoided.
宏只是做非常基本的标记替换,所以
相当于
Macros just do very basic token substitution, so
is equivalent to
让我们展开宏:
与 C 中运算符优先级的方式相比
,除数在加法之前执行,使得 #2 (1/x) + 10 而不是 1 / (x + 10)。这就是为什么你应该总是给你的宏加上括号。
Lets expand the macros:
versus
The way operator precedence is done in C, the divisor is performed before the addition is, making #2 (1/x) + 10 instead of 1 / (x + 10). That is why you should always parenthesize your macros.