布尔为int的转换 [英] bool to int conversion
问题描述
如何便携式是这种转换。我可以肯定地说这两个断言通过?
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
toint
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 valuetrue
is converted to one.
As for C, as far as I know there is no
bool
in C. (before 1999) Sobool
toint
conversion is relevant in C++ only. In C,4<5
evaluates toint
value, in this case the value is1
,4>5
would evaluate to0
.EDIT: Jens in the comment said, C99 has
_Bool
type.bool
is a macro defined instdbool.h
header file.true
andfalse
are also macro defined instdbool.h
.§7.16 from C99 says,
The macro
bool
expands to _Bool.[..]
true
which expands to the integer constant1
,false
which expands to the integer constant0
,[..]
这篇关于布尔为int的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!