C++中bool型变量按位取反结果总是为true

#include <iostream>
using namespace std;

int main()
{
    cout << sizeof(bool) << endl;   //1,一个字节,8 bit

    bool a = false;
    cout << a << endl;  //0
    a = ~a;
    cout << a << endl;  //1
    a = ~a;
    cout << a << endl;  //1

    bool b = 0xFF;
    printf("%x\n", b);  //1
    b = ~b;
    printf("%x\n", b);  //1

    int c = 0xFF;
    printf("%x\n", c);  //ff
    c = ~c;
    printf("%x\n", c);  //ffffff00
    return 0;
}

bool类型的值永远只有:

  • true:0000 0001

  • false:0000 0000

任何数值,在保存到bool变量后,都会转换成由末位bit表示的bool值,非0转换成true,0转换成false