tilde operator returning -1, -2 instead of 0, 1 respectively

江枫思渺然 提交于 2019-12-01 18:41:49

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!