Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing a boolean value in c++

Tags:

c++

When I run this simple code,

int main(int argc, const char * argv[])
{
      bool digit(true);
      std::cout << digit << " " << ~digit << std::endl;
}

The output is

1 -2

I was expecting 1 and 0 (for true and false). Am I missing something here?

like image 970
Nikhil J Joshi Avatar asked Feb 08 '26 03:02

Nikhil J Joshi


2 Answers

~ performs bitwise negation. The operand is promoted (in this case) to int, and all the bits are inverted. 1 has a binary representation of 00....001, so this gives the binary value 11....110, which is interpreted (on most modern computers) as -2.

Use ! for logical negation.

like image 193
Mike Seymour Avatar answered Feb 12 '26 04:02

Mike Seymour


~ is the bitwise not (or bit inversion) operator. The logical not operator is '!'.

    cout << !digit;
like image 45
SirGuy Avatar answered Feb 12 '26 03:02

SirGuy