ES.40: Avoid complicated expressions
ES.40:避免複雜的表達式
Reason(原因)
Complicated expressions are error-prone.
複雜的表達式容易引發錯誤。
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.
上述代碼中的有些表達式無論在什麼情況下都是不好的(例如,它們依賴未定義的行爲)。其他只是過於複雜,並且/或者不常見,從而使優秀的程序員也會錯誤理解或者匆忙中漏掉問題。
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++收緊了運算次序規則(除了賦值時從右到左之外都是從左到右,同時函數參數的運算次序是未定義的,參見ES.43),但是這也不會改變複雜的表達式可能引起混亂的事實。
Note(注意)
A programmer should know and use the basic rules for expressions.
程序員應該理解並運用關於表達式的基本準則。
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
-
結果依賴於不易察覺的優先度規則。
-
uses undefined behavior (can we catch all undefined behavior?)
-
使用了未定義的行爲(我們能找到未定義的行爲麼?)
-
implementation defined behavior?
-
又實現決定的行爲。
-
???
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es40-avoid-complicated-expressions
覺得本文有幫助?歡迎點贊並分享給更多的人。
閱讀更多更新文章,請關注微信公衆號【面向對象思考】