为什么使用 not 运算符时警告 "forcing value to bool 'true' or 'false'" 消失了?

Why warning "forcing value to bool 'true' or 'false'" disappears when using not operator?

考虑使用 Visual Studio 2015 编译的以下代码:

#include <iostream>
#include <cassert>

void foo( bool b )
{
    std::cout << b;
}

int main()
{
    int a;

    foo( a = 2 );       // getting warning #4800
    foo( !(a = 2) );    // not getting any warning

    return 0;
}

foo( a = 2 ) 产生警告 4800 'int': forcing value to bool 'true' or 'false',正常。

但是 foo( !(a = 2) ) 不会产生警告。为什么?在某些时候有一个 int 到 bool cast!

foo(a = 2)等同于bool b = (a = 2)。表达式a = 2 returns 一个a,所以它等价于

a = 2;
bool b = a; //Conversion of 'int' to 'bool' -> Warning!

foo(!(a = 2)) 等同于 bool b = !(a = 2)。表达式 a = 2 returns a:

a = 2;
bool b = !a; //'!a' is legal => It returns a bool -> No warning!

请注意,您可以将 operator! 应用于 int,这会否定 int,因此 returns 会成为 bool。这就是为什么没有性能警告。