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 吗?
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
