负数在 C/C++ 中返回 false 吗?

2022-01-19 00:00:00 c boolean c++

在 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 to true. 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.

相关文章