C++核心准则ES.40:避免复杂的表达式

2020-05-20 00:16:40 浏览数 (1)

ES.40: Avoid complicated expressions

ES.40:避免复杂的表达式

Reason(原因)

Complicated expressions are error-prone.

复杂的表达式容易引发错误。

Example(示例)
代码语言:javascript复制
// 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(示例)
代码语言:javascript复制
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

0 人点赞