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

网友投稿 543 2022-10-13

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

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

ES.40: Avoid complicated expressions

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

Reason(原因)

Complicated expressions are error-prone.

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

Example(示例)

// bad: assignment hidden in subexpressionwhile ((c = getc()) != -1)// bad: two non-local variables assigned in sub-expressionswhile ((cin >> c1, cin >> c2), c1 == c2)// better, but possibly still too complicatedfor (char c1, c2; cin >> c1 >> c2 && c1 == c2;)// OK: if i and j are not aliasedint x = ++i + ++j;// OK: if i != j and i != kv[i] = v[j] + v[k];// bad: multiple assignments "hidden" in subexpressionsx = a + (b = f()) + (c = g()) * 7;// bad: relies on commonly misunderstood precedence rulesx = a & b + c * d && e ^ f == 7;// bad: undefined behaviorx = 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; // OKauto t1 = k * y; // bad: unnecessarily verbosex = t1 + z;if (0 <= x && x < max) // OKauto t1 = 0 <= x; // bad: unnecessarily verboseauto 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​​

觉得本文有帮助?欢迎点赞并分享给更多的人。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:全唐诗分析程序
下一篇:go 爬虫框架 (框架思路参考 python scrapy)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~