做负数在C / C返回false ++? [英] Do negative numbers return false in C/C++?
问题描述
在评估整数在C / C ++布尔都是负数真的还是假的?难道他们总是真/假,无论编译器?
所有非零值将被转换为真正
和零值假
。随着负数为非零,它们都转换为真正
。
从C ++ 11标准(重点煤矿)报价:
4.12布尔转换[conv.bool]
1的算术,无范围枚举,指针,或指针的prvalue
为成员类型可以转换为bool类型的prvalue。 零
值,空指针值或空成员指针值转换
到假
;任何其他的值转换为真正
。 A型prvalue
的std :: nullptr_t可转换为bool类型的prvalue;该
得到的值是假的。
块引用>
他们是永远真/假,无论编译器?
块引用>您将只能得到上述担保时,你的编译器是符合标准的,或者至少与标准的特定部分的规定。在实践中,所有的编译器有这个标准的行为,所以没有太多的担心。
When evaluating integers as booleans in C/C++, are negative numbers true or false? Are they always true/false regardless of compilers?
解决方案All non-zero values will be converted to
true
, and zero values tofalse
. With negative numbers being non-zero, they are converted totrue
.Quoting from the C++11 standard (emphasis mine):
4.12 Boolean conversions [conv.bool]
1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to
false
; any other value is converted totrue
. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.
Are they always true/false regardless of compilers?
You will only get the above guarantee when your compiler is standards-compliant, or at least, complies with this specific part of the standard. In practice, all compilers have this standard behavior, so there isn't much to worry about.
这篇关于做负数在C / C返回false ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!