Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 865
vikiiii Avatar asked Jun 17 '13 13:06

vikiiii


People also ask

How does a complement operator work?

The one's complement operator ( ~ ), sometimes called the bitwise complement operator, yields a bitwise one's complement of its operand. That is, every bit that is 1 in the operand is 0 in the result. Conversely, every bit that is 0 in the operand is 1 in the result.

How does complement operator work in Python?

Bitwise one's complement operator (~) Bitwise one's compliment operator will invert the binary bits. If a bit is 1, it will change it to 0. If the bit is 0, it will change it to 1.

How do you use Bitwise complement operator?

Bitwise Complement Operator (~ tilde) The bitwise complement operator is a unary operator (works on only one operand). It takes one number and inverts all bits of it. When bitwise operator is applied on bits then, all the 1's become 0's and vice versa. The operator for the bitwise complement is ~ (Tilde).


2 Answers

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.

like image 106
Mark B Avatar answered Oct 10 '22 04:10

Mark B


You probably want to do this:

b = !b;

which is logical negation. What you did is bitwise negation of a bool cast to an integer. The second time the statement b = ~b; is executed, the prior value of b is true. Cast to an integer this gives 1 whose bitwise complement is -2 and hence cast back to bool true. Therefore, true values of b will remain true while false values will be assigned true. This is due to the C legacy.

like image 23
Ralph Tandetzky Avatar answered Oct 10 '22 05:10

Ralph Tandetzky