문제

I'm kind of puzzled by this. I thought the ~ operator in C++ was supposed to work differently (not so Matlab-y). Here's a minimum 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's my output:

1-2
0-1

I hope someone will have some insight into this.

도움이 되었습니까?

해결책

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

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

Note that even though you start with a bool, operator ~ causes the value to be promoted to an int by the rules of integer promotions. If you need to invert a bool to a bool, use operator ! instead of ~.

다른 팁

~ is bitwise NOT operator which means it flips all the bits. For boolean NOT, you should be using ! operator

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top