bool 上的 C++ 代字号运算符

C++ Tilde Operator on bool

我完成了 LinkedIn C++ 评估并得到了以下问题:


执行这段代码的结果是什么?

bool x=true, x=false;

if(~x || y) {
    /*part A*/
}
else {
   /*part B*/
}

我不知道答案是什么,但我认为应该显示“B”,对吗?

我认为通过“~”,x 被反转(“按位非”)因此不再是“真”

但是当我 运行 代码时,我得到“A”:

代码:

#include <iostream>

int main()
{

    bool x = true, y = false;

    std::cout << "x: " << x << std::endl;
    std::cout << "~x: " << ~x << std::endl;

    if (~x || y) {
        std::cout << "A" << std::endl;
    }
    else {
        std::cout << "B" << std::endl;
    }

    return 0;
}

输出:

x: 1
~x: -2
A

谁能给我解释一下?

在这个表达式中

~x

对 bool 类型的操作数 x 应用了整数提升。提升的结果是 int 类型的对象,其值等于 1,如(二进制)

00000000 00000000 00000000 00000001 

运算符~对位取反你会得到

11111111 11111111 11111111 11111110

来自 C++ 14 标准(5.3.1 一元运算符)

10 The operand of ~ shall have integral or unscoped enumeration type; the result is the one’s complement of its operand. Integral promotions are performed. The type of the result is the type of the promoted operand.

和(4.5 积分促销)

6 A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.

7 These conversions are called integral promotions.

由于此值不等于 0,因此用作逻辑 OR 运算符的操作数,它被隐式转换为布尔值 true。

来自 C 标准(5.15 逻辑或运算符)

1 The || operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). It returns true if either of its operands is true, and false otherwise. Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.

and (4.12 布尔转换)

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. 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.