布尔为int的转换 [英] bool to int conversion

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

问题描述

如何便携式是这种转换。我可以肯定地说这两个断言通过?

  INT X = 4℃; 5;
断言(X == 1);X = 4大于5;
断言(X == 0);

不要问为什么。我知道这是丑陋的。谢谢你。


解决方案

  INT X = 4℃; 5;

完全便携。标准的一致性。 布尔 INT 的转换是隐含的!

§4.7/ 4来自C ++标准说(积分的转换的)


  

如果来源类型为布尔,值 转换到零
  值 真正转换一个



至于C,据我知道有没有布尔在C.(1999年以前),所以,布尔 INT 的转换是在C ++相关只。在C, 4℃; 5 计算结果为 INT 值,在此情况下,该值为 1 4方式> 5 将评估为 0

编辑:延斯在注释中说,C99具有 _Bool 键入。 布尔 stdbool.h 头文件中定义的宏。 真正 stdbool.h 也定义的宏

§7.16从C99说:


  

布尔 扩展到_Bool。


  
  

[..] 真正 它扩展成整型常量的 1
  它扩展成整型常量的 0 ,[..]


How portable is this conversion. Can I be sure that both assertions pass?

int x = 4<5;
assert(x==1);

x = 4>5;
assert(x==0);

Don't ask why. I know that it is ugly. Thank you.

解决方案

int x = 4<5;

Completely portable. Standard conformant. bool to int conversion is implicit!

§4.7/4 from the C++ Standard says (Integral Conversion)

If the source type is bool, the value false is converted to zero and the value true is converted to one.


As for C, as far as I know there is no bool in C. (before 1999) So bool to int conversion is relevant in C++ only. In C, 4<5 evaluates to int value, in this case the value is 1, 4>5 would evaluate to 0.

EDIT: Jens in the comment said, C99 has _Bool type. bool is a macro defined in stdbool.h header file. true and false are also macro defined in stdbool.h.

§7.16 from C99 says,

The macro bool expands to _Bool.

[..] true which expands to the integer constant 1, false which expands to the integer constant 0,[..]

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

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