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

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

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