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
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.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With