这段 C 代码中的括号如何使结果如此不同?

发布于 2025-01-03 07:21:12 字数 370 浏览 2 评论 0原文

这段代码的输出:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

樱花落人离去 2025-01-10 07:21:12

宏替换的扩展如下:

y = RECIPROCAL_1(x+10.0)

becomes

y = 1/(x+10.0);

y = RECIPROCAL_2(x+10.0)

becomes

y = 1/x+10.0;

因为/ 的优先级高于+,所以y 的值不同。

这是一个很好的例子,说明了为什么挑剔的程序员在没有其他解决方案可行的情况下只使用宏。即便如此,那些觉得有必要使用宏的挑剔的程序员总是会使用足够的括号来确保避免此类陷阱。

The macro substitutions are expanded like this:

y = RECIPROCAL_1(x+10.0)

becomes

y = 1/(x+10.0);

and

y = RECIPROCAL_2(x+10.0)

becomes

y = 1/x+10.0;

Because / has a higher precedence that + the values for y 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.

最后的乘客 2025-01-10 07:21:12

宏只是做非常基本的标记替换,所以

#define RECIPROCAL_2(x)     1/x
  y = RECIPROCAL_2(x+10.0);

相当于

  y = 1/x+10.0;

Macros just do very basic token substitution, so

#define RECIPROCAL_2(x)     1/x
  y = RECIPROCAL_2(x+10.0);

is equivalent to

  y = 1/x+10.0;
素年丶 2025-01-10 07:21:12

让我们展开宏:

y = 1/(x + 10)

与 C 中运算符优先级的方式相比

y = 1/x + 10

,除数在加法之前执行,使得 #2 (1/x) + 10 而不是 1 / (x + 10)。这就是为什么你应该总是给你的宏加上括号。

Lets expand the macros:

y = 1/(x + 10)

versus

y = 1/x + 10

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文