When I run this simple code,
int main(int argc, const char * argv[])
{
bool digit(true);
std::cout << digit << " " << ~digit << std::endl;
}
The output is
1 -2
I was expecting 1 and 0 (for true and false). Am I missing something here?
~ performs bitwise negation. The operand is promoted (in this case) to int, and all the bits are inverted. 1 has a binary representation of 00....001, so this gives the binary value 11....110, which is interpreted (on most modern computers) as -2.
Use ! for logical negation.
~ is the bitwise not (or bit inversion) operator. The logical not operator is '!'.
cout << !digit;
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