Do negative numbers return false in C/C++?(负数在 C/C++ 中返回 false 吗?)
问题描述
在 C/C++ 中将整数计算为布尔值时,负数是真还是假?无论编译器如何,它们总是对/错吗?
所有非零值都将转换为true
,零值将转换为false
.负数不为零,它们被转换为 true
.
引用 C++11 标准(强调我的):
<块引用>4.12 布尔转换 [conv.bool]
1 算术、无范围枚举、指针或指针的纯右值to 成员类型可以转换为 bool 类型的纯右值.零值、空指针值或空成员指针值被转换假
;任何其他值都将转换为 true
. 类型的纯右值std::nullptr_t 可以转换为 bool 类型的纯右值;这结果值为假.
<小时><块引用>
无论编译器如何,它们总是真/假吗?
只有当您的编译器符合标准或至少符合标准的这一特定部分时,您才能获得上述保证.实际上,所有编译器都有这种标准行为,所以不用担心.
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 to false
. With negative numbers being non-zero, they are converted to true
.
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 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:负数在 C/C++ 中返回 false 吗?


- Stroustrup 的 Simple_window.h 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 近似搜索的工作原理 2021-01-01
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07