微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

在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.

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

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

原文地址:https://www.jb51.cc/c/111220.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐