在 C/C++ 中将 int 转换为 bool

2023-12-06

我知道在 C 和 C++ 中,当将 bool 转换为 int 时,(int)true == 1 and (int)false == 0。我想知道是否可以反向投射......

在下面的代码中,在使用 Visual Studio 2013 和 Keil µVision 5 编译的 .c 文件中,以下所有断言对我来说都成立。(bool)2 == true.

C 和 C++ 标准对于将非零、非一整数转换为布尔值有何规定?此行为是否已指定?请附上引文。

#include <stdbool.h>
#include <assert.h>

void TestBoolCast(void)
{
    int i0 = 0, i1 = 1, i2 = 2;

    assert((bool)i0 == false);
    assert((bool)i1 == true);
    assert((bool)i2 == true);

    assert(!!i0 == false);
    assert(!!i1 == true);
    assert(!!i2 == true);
}

Not的副本对于任何 C++ 编译器,我可以假设 (bool)true == (int)1 吗?:

  1. 反向转换(int --> bool)。
  2. 那里没有讨论非零、非一值。

0 values of basic types (1)(2)map to false.

其他值映射到true.

该约定是在原始 C 中通过其流程控制语句建立的; C 当时没有布尔类型。


假设函数返回值是一个常见的错误,false表示失败。但特别是从main it's false这表明成功。我已经多次看到这种错误,包括在 D 语言的 Windows 入门代码中(当像 Walter Bright 和 Andrei Alexandrescu 这样的人犯错时,那就太糟糕了easy出错),因此请注意。


无需投射到bool对于内置类型,因为该转换是隐式的。然而,Visual C++(Microsoft 的 C++ 编译器)倾向于为此发出性能警告(!),这是一个纯粹的愚蠢警告。强制转换不足以将其关闭,而是通过双重否定进行转换,即return !!x,效果很好。一个人可以读!!作为“转换为bool” 运算符,就像-->可以读作“前往”。对于那些深入了解运算符符号的可读性的人。 ;-)


1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.”
2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C/C++ 中将 int 转换为 bool 的相关文章

随机推荐