为什么 sizeof(!0) 打印 1 而不是 4?

Why does sizeof(!0) print 1 instead of 4?

#include <iostream>

int main()
{
    std::cout<<sizeof(0);
    return 0;
}

这里,sizeof(0)在C++中是4,因为0是一个整数右值。

但是,如果我这样写:

std::cout<<sizeof(!0);

这里,sizeof(!0)就是1。但是,!0 意味着它打印 1,这也是 int 类型。

那么,为什么 sizeof(!0) 打印 1 而不是 4?我在这里想念什么?

!0 是一个 bool

sizeof(bool) 取决于实现。

logical negation运算符:

! rhs

If the operand is not bool, it is converted to bool using contextual conversion to bool: it is only well-formed if the declaration bool t(arg) is well-formed, for some invented temporary t.

The result is a bool prvalue.

并且 sizeof (bool) 是实现定义的 在您的实现中是 1。

通过在整数值前添加 !,您可以将其转换为布尔值 - 可以使用单个字节表示。

当我们写0时它是一个整数,但是当我们写!0时它隐式地将整数转换为布尔值。 ! 运算符将任何整数转换为布尔值,您可以尝试编写 !1!2...这些都给出 1 字节的大小。 如果你想知道 !0 的大小作为一个整数,你可以将它转换为

sizeof(int(!0));