运算符优先级(按位 '&' 低于 '==')

发布于 2024-10-11 21:48:46 字数 62 浏览 6 评论 0原文

在 C 编程语言中,为什么按位运算符(& 和 |)的优先级低于等号运算符(==)?这对我来说没有意义。

In the C programing language, why do the bitwise operators (& and |) have lower precedence than the equality operator (==)? It does not make sense to me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

野生奥特曼 2024-10-18 21:48:46

您需要询问Brian Kernighan丹尼斯·里奇
来自论坛帖子运算符优先级

&&和||后来添加了运算符
因为他们的“短路”行为。丹尼斯·里奇承认
回顾一下按位运算符的优先级应该有
添加逻辑运算符后发生更改。但与几个
当时已有数百千字节的 C 源代码,并且
三台计算机的安装基数,丹尼斯认为太大了
C 语言的变化...

那么,这可能是一个原因?我猜测,由于存在多层按位优先级(与关系比较不同),因此它是自……永远……存在的,而且从未得到纠正。

You need to ask Brian Kernighan or Dennis Ritchie.
From the forum post Operator precedence:

The && and || operators were added later
for their "short-circuiting" behavior. Dennis Ritchie admits in
retrospect that the precedence of the bitwise operators should have
been changed when the logical operators were added. But with several
hundred kilobytes of C source code in existence at that point and an
installed base of three computers, Dennis thought it would be too big
of a change in the C language...

So, that might be a reason? I'm guessing since there are several layers of bitwise precedence (unlike relational comparisons) that it's cruft that's existed since...forever...and just was never corrected.

刘备忘录 2024-10-18 21:48:46

对于 Dennis Ritchie 来说也没有意义,回想起来。

&&和||被添加到语言之后 |和 &,并且出于兼容性原因保持优先级。

It doesn't make sense to Dennis Ritchie, either, in retrospect.

&& and || were added to the language after | and &, and precedence was maintained for reasons of compatibility.

拥醉 2024-10-18 21:48:46

对于为什么 K&R 选择他们所做的优先级,我没有权威的答案。一个相当有意义的示例是:

if (x == 1 & y == 0) {
    /* ... */
}

由于这是按位 AND 运算符,因此它使用非短路评估模式,就像

if (x == 1 | y == 0) {
    /* ... */
}

使用非短路 OR 运算符一样。这可能就是为什么他们选择以这种方式设置优先级组,但我同意你的观点,回想起来这似乎不是一个好主意。

I don't have an authoritative answer as to why K&R chose the precedence they did. One example that makes a fair amount of sense would be this one:

if (x == 1 & y == 0) {
    /* ... */
}

Since this is the bitwise AND operator, it uses a non-short-circuiting evaluation mode, as would

if (x == 1 | y == 0) {
    /* ... */
}

use the non-short-circuiting OR operator. This is probably why they chose to have the precedence group this way, but I agree with you that in retrospect it doesn't seem like a good idea.

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