条件分配给布尔 [英] Condition assignment to boolean

查看:180
本文介绍了条件分配给布尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仿效​​布尔值可以做到这样的:

Emulating booleans in C can be done this way:

int success;
success = (errors == 0 && count > 0);
if(success)
   ...

使用 stdbool.h 收入以下可以做的:

With stdbool.h included following could be done:

bool success;
success = (errors == 0 && count > 0) ? true : false;
if(success)
   ...

据我了解的逻辑和比较操作应该返回1或0。
此外, stdbool.h 常量应该这样定义:真正的== 1 =假= 0

From what I understand logical and comparison operators should return either 1 or 0. Also, stdbool.h constants should be defined so that true == 1 and false == 0.

因此​​,下面应该工作:

Thus following should work:

bool success;
success = (errors == 0 && count > 0);
if(success)
   ...

和它上了我与测试它的编译器工作。但它是安全的假设它是便携式code? (假设 stdbool.h 存在)

And it does work on compilers that I have tested it with. But is it safe to assume it is portable code? (Assume that stdbool.h exists)

是C ++编译器不同的情况为布尔是内部类型?

Is the situation different on C++ compilers as bool is internal type?

推荐答案

这是安全的假设。在C99,在转换到 _Bool 类型,所有非零值转换为1,这在6.3.1.2节在C99标准描述。平等和关系运算符(如 == > = 等),保证导致1或0为好。这是在第6.5.8和6.5.9描述。

It is safe to assume. In C99, upon conversion to the _Bool type, all non-zero values are converted to 1. This is described in section 6.3.1.2 in the C99 standard. The equality and relational operators (e.g. ==, >=, etc) are guaranteed to result in either 1 or 0 as well. This is described in section 6.5.8 and 6.5.9.

有关C ++中,布尔类型是一个真正的布尔类型,其中值转换为真正假 == 操作等来一个<$> C $ C>布尔,并期望它的工作,因为关系和比较操作导致布尔反正。当真正转换为整数类型它转换为1。

For C++, the bool type is a real Boolean type where values are converted to true or false rather than 1 or 0, but it is still safe to assign the result of an == operation etc. to a bool and expect it to work, because the relational and comparison operators result in a bool anyway. When true is converted to an integer type it is converted to 1.

这篇关于条件分配给布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆