前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.41: 如果对操作符的优先级有疑问,使用括号明确运算次序

C++核心准则ES.41: 如果对操作符的优先级有疑问,使用括号明确运算次序

作者头像
面向对象思考
发布2020-05-20 00:16:24
2890
发布2020-05-20 00:16:24
举报

ES.41: If in doubt about operator precedence, parenthesize

ES.41: 如果对操作符的优先级有疑问,使用括号明确运算次序

Reason(原因)

Avoid errors. Readability. Not everyone has the operator table memorized.

避免错误。可读性。不是所有人都记住操作符表。

Example(示例)

代码语言:javascript
复制
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.

注意:我们建议程序员记住数学运算,逻辑运算的优先级(而不适用括号,译者注)。但认为位操作和其他操作符混用时应该使用括号。

代码语言:javascript
复制
if ((a & flag) != 0)  // OK: works as intended
Note(注意)

You should know enough not to need parentheses for:

你应该可以理解下面的代码不需要括号。

代码语言:javascript
复制
if (a < 0 || a <= max) {
    // ...
}
Enforcement(实施建议)
  • Flag combinations of bitwise-logical operators and other operators.
  • 标记将位操作和其他操作混用的情况。
  • Flag assignment operators not as the leftmost operator.
  • 标记赋值运算符不在最左侧的情况。
  • ???

链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es40-avoid-complicated-expressions

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-05-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ES.41: If in doubt about operator precedence, parenthesize
  • Reason(原因)
    • Note(注意)
      • Enforcement(实施建议)
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档