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

Casting int to bool in C/C++

我知道在C和C ++中,将布尔值转换为int,(int)true == 1(int)false == 0时。 我想知道反向铸造...

在下面的代码中,以下所有断言在使用Visual Studio 2013和KeilμVision5编译的.c文件中对我而言都是正确的。请注意(bool)2 == true

对于将非零,非一整数转换为布尔值,C和C ++标准怎么说? 是否指定了此行为? 请包括引文。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdbool.h>
#include

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);
}

我不能为任何C ++编译器都假设(bool)true ==(int)1吗?

  • 反向投放(int-> bool)。
  • 那里没有讨论非零,非一的值。

  • 基本类型(1)(2)的0值映射到false

    其他值映射到true

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

    假定作为函数返回值的false表示失败是一个常见错误。但是特别是从mainfalse表示成功。我已经看过很多次做错了,包括在Windows的D语言启动代码中(当您遇到Walter Bright和Andrei Alexandrescu之类的人弄错了,那么就很容易犯错),因此请注意当心。

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

    1)C ++ 14§4.12/ 1将零值,空指针值或空成员指针值转换为false;其他任何值都将转换为true。对于直接初始化(8.5),可以将类型std::nullptr_t的prvalue转换为类型bool的prvalue。结果值为false
    2)C99和C11§6.3.1.2/ 1将任何标量值转换为_Bool时,如果该值等于0,则结果为0;否则,结果为0。否则,结果为1。


    以下引用了C11标准(最终草案)。

    6.3.1.2: When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

    bool(对于C,由stdbool.h映射为内部名称_Bool)本身是一个无符号整数类型:

    ... The type _Bool and the unsigned integer types that correspond to the standard signed integer types are the standard unsigned integer types.

    根据6.2.5p2:

    An object declared as type _Bool is large enough to store the values 0 and 1.

    AFAIK这些定义在语义上与C ++相同-内置(!)名称略有不同。对于C ++,bool,对于C,_Bool

    请注意,C不像C ++那样使用术语rvalues。但是,在C中,指针是标量,因此将指针分配给_Bool的行为与C ++中的行为相同。


    删除警告的另一种方法(至少在MS Visual Studio 2019 C ++中)是使用三元运算符并将值直接设置为true或false:

    1
    2
    int i = 3; // Or another value
    bool b = (i ? true : false);

    或者更明确地说:

    1
    2
    int i = 3; // Or another value
    bool b = (i == 0 ? false : true);