Apr 1, 2015

[C++] ~ boolean type

Does using bitwise not operator (~) on boolean values invoke Undefined Behavior?
No, it's well defined behavior.

5.3.1/10 The operand of ~ shall have integral or unscoped enumeration type; the result is the one’s complement of its operand. Integral promotions are performed. [emphasis mine]
4.5/6 A prvalue of type bool can be converted to a prvalue of type int, with falsebecoming zero and true becoming one.
4.5/7 These conversions are called integral promotions.
~false is an int with a bit pattern consisting of all ones - one's complement of a bit pattern representing 0, namely all zeros (as required by 3.9.1/7.)

~true is an int that's one's complement of the bit representation of 1 - namely, all ones with the least significant bit zero.

Both these values will evaluate to true in boolean context.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.