ES.41: If in doubt about operator precedence, parenthesize
ES.41: 如果对操作符的优先级有疑问,使用括号明确运算次序
Reason(原因)
Avoid errors. Readability. Not everyone has the operator table memorized.
避免错误。可读性。不是所有人都记住操作符表。
Example(示例)
代码语言:javascript复制const unsigned int flag = 2;
unsigned int a = flag;
if (a & flag != 0) // bad: means a&(flag != 0)
Note: We recommend that programmers know their precedence table for the arithmetic operations, the logical operations, but consider mixing bitwise logical operations with other operators in need of parentheses.
注意:我们建议程序员记住数学运算,逻辑运算的优先级(而不适用括号,译者注)。但认为位操作和其他操作符混用时应该使用括号。
代码语言:javascript复制if ((a & flag) != 0) // OK: works as intended
Note(注意)
You should know enough not to need parentheses for:
你应该可以理解下面的代码不需要括号。
代码语言:javascript复制if (a < 0 || a <= max) {
// ...
}
Enforcement(实施建议)
- Flag combinations of bitwise-logical operators and other operators.
- 标记将位操作和其他操作混用的情况。
- Flag assignment operators not as the leftmost operator.
- 标记赋值运算符不在最左侧的情况。
- ???
链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es40-avoid-complicated-expressions