C++核心準(zhǔn)則ES.41: 如果對(duì)操作符的優(yōu)先級(jí)有疑問(wèn),使用括號(hào)明確運(yùn)算...

ES.41: If in doubt about operator precedence, parenthesize
ES.41:?如果對(duì)操作符的優(yōu)先級(jí)有疑問(wèn),使用括號(hào)明確運(yùn)算次序
Reason(原因)
Avoid errors. Readability. Not everyone has the operator table memorized.
避免錯(cuò)誤??勺x性。不是所有人都記住操作符表。
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.
注意:我們建議程序員記住數(shù)學(xué)運(yùn)算,邏輯運(yùn)算的優(yōu)先級(jí)(而不適用括號(hào),譯者注)。但認(rèn)為位操作和其他操作符混用時(shí)應(yīng)該使用括號(hào)。
if ((a & flag) != 0) // OK: works as intended
Note(注意)
You should know enough not to need parentheses for:
你應(yīng)該可以理解下面的代碼不需要括號(hào)。
if (a < 0 || a <= max) {
// ...
}
Enforcement(實(shí)施建議)
Flag combinations of bitwise-logical operators and other operators.
標(biāo)記將位操作和其他操作混用的情況。
Flag assignment operators not as the leftmost operator.
標(biāo)記賦值運(yùn)算符不在最左側(cè)的情況。
???
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es40-avoid-complicated-expressions
覺(jué)得本文有幫助?請(qǐng)分享給更多人。
關(guān)注微信公眾號(hào)【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_(kāi)發(fā),面向?qū)ο笏伎迹?/span>
