C++核心準則ES.40:避免復雜的表達式

ES.40: Avoid complicated expressions
ES.40:避免復雜的表達式
Reason(原因)
Complicated expressions are error-prone.
復雜的表達式容易引發(fā)錯誤。
Example(示例)
// bad: assignment hidden in subexpression
while ((c = getc()) != -1)
// bad: two non-local variables assigned in sub-expressions
while ((cin >> c1, cin >> c2), c1 == c2)
// better, but possibly still too complicated
for (char c1, c2; cin >> c1 >> c2 && c1 == c2;)
// OK: if i and j are not aliased
int x = ++i + ++j;
// OK: if i != j and i != k
v[i] = v[j] + v[k];
// bad: multiple assignments "hidden" in subexpressions
x = a + (b = f()) + (c = g()) * 7;
// bad: relies on commonly misunderstood precedence rules
x = a & b + c * d && e ^ f == 7;
// bad: undefined behavior
x = x++ + x++ + ++x;
Some of these expressions are unconditionally bad (e.g., they rely on undefined behavior). Others are simply so complicated and/or unusual that even good programmers could misunderstand them or overlook a problem when in a hurry.
上述代碼中的有些表達式無論在什么情況下都是不好的(例如,它們依賴未定義的行為)。其他只是過于復雜,并且/或者不常見,從而使優(yōu)秀的程序員也會錯誤理解或者匆忙中漏掉問題。
Note(注意)
C++17 tightens up the rules for the order of evaluation (left-to-right except right-to-left in assignments, and the order of evaluation of function arguments is unspecified; see ES.43), but that doesn't change the fact that complicated expressions are potentially confusing.
C++收緊了運算次序規(guī)則(除了賦值時從右到左之外都是從左到右,同時函數(shù)參數(shù)的運算次序是未定義的,參見ES.43),但是這也不會改變復雜的表達式可能引起混亂的事實。
Note(注意)
A programmer should know and use the basic rules for expressions.
程序員應該理解并運用關(guān)于表達式的基本準則。
Example(示例)
x = k * y + z; // OK
auto t1 = k * y; // bad: unnecessarily verbose
x = t1 + z;
if (0 <= x && x < max) // OK
auto t1 = 0 <= x; // bad: unnecessarily verbose
auto t2 = x < max;
if (t1 && t2) // ...
Enforcement(實施建議)
Tricky. How complicated must an expression be to be considered complicated? Writing computations as statements with one operation each is also confusing. Things to consider:
難辦。一個表達式到底復雜到什么程度算復雜?每個語句中只包含一個操作也會導致難以理解。需要考慮一下因素:
side effects: side effects on multiple non-local variables (for some definition of non-local) can be suspect, especially if the side effects are in separate subexpressions
副作用:可以懷疑多個非局部變量的副作用,特別是副作用存在于獨立的子表達式中的情況。
writes to aliased variables
像變量的別名寫入。
more than N operators (and what should N be?)
多余N個操作符(問題是N應該是幾?)
reliance of subtle precedence rules
結(jié)果依賴于不易察覺的優(yōu)先度規(guī)則。
uses undefined behavior (can we catch all undefined behavior?)
使用了未定義的行為(我們能找到未定義的行為么?)
implementation defined behavior?
又實現(xiàn)決定的行為。
???
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es40-avoid-complicated-expressions
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
