c++booleancomplement

Why is the complement operator not working when bool = true?


I have written this C++ program, and I am not able to understand why it is printing 1 in the third cout statement.

#include<iostream>

using namespace std;

int main()
{
    bool b = false;
    cout << b << "\n";  // Print 0
    b = ~b;
    cout << b << "\n"; // Print 1
    b = ~b;
    cout << b << "\n"; // Print 1 **Why?**
    return 0;
}

Output:

0
1
1

Why is it not printing the following?

0
1
0

Solution

  • This is due to C legacy operator mechanization (also recalling that ~ is bitwise complement). Integral operands to ~ are promoted to int before doing the operation, then converted back to bool. So effectively what you're getting is (using unsigned 32 bit representation) false -> 0 -> 0xFFFFFFFF -> true. Then true -> 1 -> 0xFFFFFFFE -> 1 -> true.

    You're looking for the ! operator to invert a boolean value.