加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在比较期间,C bool是否转换为int?

发布时间:2020-12-16 03:29:12 所属栏目:百科 来源:网络整理
导读:在C中使用比较运算符时,bool是否转换为整数? 我问的原因是在if语句中是否始终明确地与true / false比较的问题出现了.这两个选项是: 1) if (my_bool == true) doSomething();2) if (my_bool) doSomething(); 我们认为你应该通常避免明确的比较(1),因为以下
在C中使用比较运算符时,bool是否转换为整数?

我问的原因是在if语句中是否始终明确地与true / false比较的问题出现了.这两个选项是:

1) if (my_bool == true) doSomething();
2) if (my_bool) doSomething();

我们认为你应该通常避免明确的比较(1),因为以下内容:

int myFunc(){return 4;}
if (myFunc() == true) doSomething();

如果您需要使用简单地返回非零以指示“true”的C接口,则会出现类似上面代码的内容. myFunc()示例在C中会失败,因为myFunc返回4,true为宏,为1,而4 == 1不为真.

C中的情况仍然如此吗? “等于”运算符是否将bool转换为int而不是相反?我很感激参考标准(C 11是我正在使用的),但如果它的语言版本不同,我有兴趣知道.

(我想特别询问明确的真/假比较的利弊,但这看起来似乎是主观的.)

解决方法

When using comparison operators in C++,are bools converted to ints?

是.对于关系运算符([expr.rel] / 5):

The usual arithmetic conversions are performed on operands of arithmetic or enumeration type.

对于相等运算符([expr.eq] / 6):

If both operands are of arithmetic or enumeration type,the usual arithmetic conversions are performed on
both operands;

当两个操作数都是bool时,它们都被提升为int.如果一个操作数是bool而另一个是整数类型,则bool操作数被提升为int.见[expr] / 10:

Otherwise,the integral promotions (4.5) shall be performed on both operands.

据我所知,从一开始就是如此(标准的修订版本没有区别).

我不认为对真或假进行明确比较有任何性能影响,但我不会自己做,因为我认为它是多余的,而不是产生任何好处的方式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读