<分区>
>=
和 '>' 的优先级高于 |
的直觉原因是什么? Reference .
我可以理解为什么 ||
较低,因为编写 a>b||c
很常见。但是我认为 a>b|c
会在比较之前进行 OR。这似乎并不直观。 &^|
的优先级低于直观的比较/权益运算符的示例有哪些?
<分区>
>=
和 '>' 的优先级高于 |
的直觉原因是什么? Reference .
我可以理解为什么 ||
较低,因为编写 a>b||c
很常见。但是我认为 a>b|c
会在比较之前进行 OR。这似乎并不直观。 &^|
的优先级低于直观的比较/权益运算符的示例有哪些?
最佳答案
这是一次历史事故,在The Development of the C Language ,丹尼斯·里奇写道:
Their tardy introduction explains an infelicity of C's precedence rules. In B one writes
if (a==b & c) ...
to check whether a equals b and c is non-zero; in such a conditional expression it is better that & have lower precedence than ==. In converting from B to C, one wants to replace & by && in such a statement; to make the conversion less painful, we decided to keep the precedence of the & operator the same relative to ==, and merely split the precedence of && slightly from &. Today, it seems that it would have been preferable to move the relative precedences of & and ==, and thereby simplify a common C idiom: to test a masked value against another value, one must write
if ((a&mask) == b) ...
where the inner parentheses are required but easily forgotten.
所以这是因为 B 使用 |
和 &
作为逻辑运算符,而 C 保留了这样表示的按位运算符的优先级。
关于c++ ->= 优先级高于 | 的直观原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12849094/