Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using bitwise not operator (~) on boolean values invoke Undefined Behavior?

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 ;))

like image 257
Jeremy Friesner Avatar asked Apr 01 '15 23:04

Jeremy Friesner


1 Answers

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 false becoming zero and true becoming 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.

like image 138
Igor Tandetnik Avatar answered Sep 17 '22 17:09

Igor Tandetnik