c++ ->= 优先级高于 | 的直观原因

标签 c++ c

<分区>

>= 和 '>' 的优先级高于 | 的直觉原因是什么? 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/

相关文章:

CPP 文件中的 C++11 模板定义, undefined reference

c++ - QODBC 数字的错误值

c++ - 为什么这段代码中继承的函数隐藏在基类中?

c - gl_Position 在此配置文件中不可访问?

objective-c - C 和 Objective-C - 释放无符号字符指针的正确方法

C++:从字符串中删除所有 HTML 格式?

c++ - 在 Eclipse 中突出显示 makefile

c - SendMessage WM_MOUSEMOVE 未按预期工作

c++ - 如何在不公开 C API 的情况下包装 C API?

c++ - 用于有序组合生成和排名的库?