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++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
