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 ~
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…