温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++为什么不要在条件语句中增加多余的==或!=

发布时间:2021-11-25 16:30:10 来源:亿速云 阅读:123 作者:iii 栏目:大数据

本篇内容主要讲解“C++为什么不要在条件语句中增加多余的==或!=”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++为什么不要在条件语句中增加多余的==或!=”吧!

ES.87:不要在条件语句中增加多余的==或!=

Reason(原因)

这么做可以避免冗长的代码并且减少某些错误的机会。帮助提高代码的以执行并符合习惯。

Example(示例)

从定义的角度来讲,if语句、while语句、for语句中的条件判断得到true或false的结果。数值和0比较,指针和nullptr进行比较。

// These all mean "if `p` is not `nullptr`"
if (p) { ... }            // good
if (p != 0) { ... }       // redundant `!=0`; bad: don't use 0 for pointers
if (p != nullptr) { ... } // redundant `!=nullptr`, not recommended

通常,if(p)被读作如果p是合法的,这是程序员意图的直接表达,而if(p != nullptr)却是一种冗长的表达方式。

Example(示例)

本规则在声明作为条件使用时特别有用。

if (auto pc = dynamic_cast<Circle>(ps)) { ... } // execute if ps points to a kind of Circle, good

if (auto pc = dynamic_cast<Circle>(ps); pc != nullptr) { ... } // not recommended
Example(示例)

Note that implicit conversions to bool are applied in conditions. For example:

注意可以隐式类型转换为布尔类型的运算都可以用于条件语句。例如S:

for (string s; cin >> s; ) v.push_back(s);

This invokes istream's operator bool().

这段代码利用了istream的bool()运算符。

Note(注意)

将整数和0进行显示比较通常不是冗长形式。原因是(和指针和布尔类型不同,)整数通常可以表达多于两个有意义的值。另外通常使用0(zero)表示成功。因此,最好将整数比较作为特例。

void f(int i)
{
   if (i)            // suspect
   // ...
   if (i == success) // possibly better
   // ...
}

Always remember that an integer can have more than two values.

一定记住整数可以拥有的有效值可以超过两个。

Example, bad(反面示例)

It has been noted that

已经提醒过了:

if(strcmp(p1, p2)) { ... }   // are the two C-style strings equal? (mistake!)

is a common beginners error. If you use C-style strings, you must know the <cstring> functions well. Being verbose and writing

这是一个常见的,初学者错误。如果你使用C风格字符串,以一定知道<cstring>函数。保持冗长并书写

if(strcmp(p1, p2) != 0) { ... }   // are the two C-style strings equal? (mistake!)

would not in itself save you.

也没什么帮助。

Note(注意)

The opposite condition is most easily expressed using a negation:

使用!更容易表达反逻辑:

// These all mean "if `p` is `nullptr`"
if (!p) { ... }           // good
if (p == 0) { ... }       // redundant `== 0`; bad: don't use `0` for pointers
if (p == nullptr) { ... } // redundant `== nullptr`, not recommended
Enforcement(实施建议)

Easy, just check for redundant use of != and == in conditions.

容易,只需要检查条件语句中多余的!=和==。

到此,相信大家对“C++为什么不要在条件语句中增加多余的==或!=”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI