0

I was just tinkering with use of bitwise operators on bool data type, so I wrote a simple program.

#include <iostream>

int main()
{
    bool b = 1;
    std::cout<<~b;
    return 0;
}

This code, to my surprise, gave me the output -2.

~-operator flips all the bits on variable its used on and bool only holds 2 distinct values and is made of 8 bits or 1 byte. So 0b000 is interpreted as 0 that is false and 0b111 is interpreted as 1 that is true.

So value 1 will be 0b111 and using bit-wise not(~) operator on it will flip all bits to 0b000 that is 0.

Simon Kraemer
  • 5,700
  • 1
  • 19
  • 49
  • 3
    Cannot find a good duplicate: Integer promotion happens here, everything smaller than an `int` gets promoted to an `int`. So, the `bool` `true` becomes the `int` `1`, when applying `~` on it. And this results in `-2` (every bit except the least significant is set). – mch Jul 05 '22 at 07:08
  • The output of `std::cout< – 273K Jul 05 '22 at 07:13
  • 4
    What's happened here is that you've made up some rules regarding how bools should behave. Those rules are perfectly logical, but incorrect. What actually happens is called integer promotion. Before the `~` is applied the boolean value is promoted to an `int` and since the value is true, the promoted value is one. The bitwise operation is then applied to the integer one. If interested you could read the real rules on [integral promotion](https://en.cppreference.com/w/cpp/language/implicit_conversion) – john Jul 05 '22 at 07:17
  • Not so sure if that dupliacte fits. However your basic wrong assumption that true would be `1111'1111` is wrong (that's how I understood your _original_ question, before the edit). However that's wrong. `true -> 1 -> 0000'0001` and `~0000'0001 -> 1111'1110 = -2`. See https://en.cppreference.com/w/cpp/language/implicit_conversion – Lukas-T Jul 05 '22 at 07:22
  • I learned a lot today thanks for reply. – aamir pashah Jul 05 '22 at 15:30

0 Answers0