1

I'm a beginner at using bitwise operators and bool type. I might be wrong, but I thought bool type is represented on 1 bit and can take values from {0, 1}. So, I tried the NOT (~) operator with such a variable and the results are weird for me. eg. for

    bool x = 0;
    cout << (~x);

I get -1. (I expected 1) Can you please tell me where I'm wrong and why only the ! operator does reverse the value (from 0 to 1 and from 1 to 0)?

Darius V.
  • 23
  • 5

3 Answers3

2

Most processors do not have a 1 bit wide general purpose register so when you use a boolean it takes up whatever the default register size is on that platform (ie 64 bits on most Intel and ARM computers these days, but maybe 32 bit on some embedded systems). When you negate some thing that is all zeros, you get all 1's. In twos complement this evaluates to -1 in signed decimal. Long story short, your bool is really an int and ~0 is -1

Josh Homann
  • 15,933
  • 3
  • 30
  • 33
0

The ! operator is a logical operator - hence 0 (false) is negated to 1 (true).

The ~ operator is a bitwise operator - hence every bit is negated. A bool, while notionally a single bit - can results in expressions of type int. Hence you are really negating 0.....000, which is 1...111, which is -1 (see two's complement).

dave
  • 11,641
  • 5
  • 47
  • 65
0

The bool value x is implicitly converted to an int when used in the expression ~x. And the vast majority of computers use two's complement representation of signed integers, in which ~0 is equal to -1.

The ! operator is defined so that !x has type bool rather than int, so this issue doesn't occur.

dan04
  • 87,747
  • 23
  • 163
  • 198