C++核心准则ES.41: 如果对操作符的优先级有疑问,使用括号明确运算次序

ES.41: If in doubt about operator precedence, parenthesize

ES.41: 如果对操作符的优先级有疑问,使用括号明确运算次序

 

Reason(原因)

Avoid errors. Readability. Not everyone has the operator table memorized.

避免错误。可读性。不是所有人都记住操作符表。

 

Example(示例)

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.

注意:我们建议程序员记住数学运算,逻辑运算的优先级(而不适用括号,译者注)。但认为位操作和其他操作符混用时应该使用括号。

if ((a & flag) != 0)  // OK: works as intended

Note(注意)

You should know enough not to need parentheses for:

你应该可以理解下面的代码不需要括号。

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

 


 

觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章