Tilde operator returning -1, -2 instead of 0, 1, respectively

I am a little puzzled by this. I thought the ~ operator in C ++ should work differently (not so Matlab-y). Here's a minimal working example:

#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
    bool banana = true;
    bool peach = false;
    cout << banana << ~banana << endl;
    cout << peach << ~peach << endl;
}

And here is my conclusion:

1-2
0-1

I hope someone will have some understanding of this.

+4
source share
2 answers

This is exactly what should happen: when you invert the binary representation of zero, you get a negative; when you invert the binary representation of one, you get negative two in two representations of the representation.

00000000 --> ~ --> 11111111 // This is -1
00000001 --> ~ --> 11111110 // This is -2

, bool, ~ int . a bool a bool, ! ~.

+6

~ NOT, , . boolean NOT !

0

All Articles