7

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.

castle-bravo
  • 1,389
  • 15
  • 34
  • What did you expect? That's bitwise inversion of the [two's complement](https://en.wikipedia.org/wiki/Two's_complement) representation of the value stored in memory. – leemes Feb 24 '14 at 00:20
  • `~` is the binary-not operator, so binary all zeroes becomes binary all ones, and so on. – 500 - Internal Server Error Feb 24 '14 at 00:20
  • 1
    @leemes, I expected the ~ operator to flip true to false and vice versa, and for some reason I thought I remembered using it that way in the past. It seems that ~ operates on the whole byte though - my bad. – castle-bravo Feb 24 '14 at 00:29
  • @castle-bravo I first read your question a bit wrong, namely I thought you apply the operators to integers. Then, a boolean inversion wasn't very "logical" to me as an expectation, so I didn't know what you expect. Now that I notice that you saw it like "inversion of a boolean value" it makes totally sense to me how you interpreted it! And I admit, it can be confusing. :) – leemes Feb 25 '14 at 13:30
  • @leemes, The way that I phrased the title of the question was probably what caused you to misunderstand my meaning. – castle-bravo Feb 25 '14 at 18:10
  • Exactly. I only looked at the title, should have looked more carefully. My bad ;) – leemes Feb 25 '14 at 21:10
  • [Why is a boolean 1 byte and not 1 bit of size?](https://stackoverflow.com/q/4626815/608639) – jww Jul 06 '19 at 14:11

2 Answers2

11

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 ~.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

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

anonymous
  • 1,317
  • 8
  • 7