If a C++ program applies the bitwise-not operator (~) to a boolean value, does that invoke Undefined Behavior?
E.g. is the following program well-defined?
bool f = false;
bool f2 = ~f; // is f2 guaranteed to be true, or is this UB?
bool t = true;
bool t2 = ~t; // is t2 guaranteed to be false, or is this UB?
(Yes, I know there is a ! operator that is better-suited to this sort of thing; for purposes of this question we will ignore its existence ;))
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
boolcan be converted to a prvalue of typeint, withfalsebecoming zero andtruebecoming one.4.5/7 These conversions are called integral promotions.
So ~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.) Similarly, ~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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With