Operator precedence (bitwise '&' lower than '==')

谁说胖子不能爱 提交于 2019-11-26 04:26:04

问题


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.


回答1:


You need to ask Brian Kernighan or Dennis Ritchie.
From this forum: http://bytes.com/topic/c/answers/167377-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 precendence (unlike relational comparisons) that it's cruft that's existed since...forever...and just was never corrected.




回答2:


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

http://www.lysator.liu.se/c/dmr-on-or.html

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




回答3:


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.



来源:https://stackoverflow.com/questions/4685072/operator-precedence-bitwise-lower-than

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!