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 ;))
Best Answer
So
~false
is anint
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 anint
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 totrue
in boolean context.