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 吗?
基础教程推荐
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
