Is there a "very bad thing" that can happen &&= and ||= were used as syntactic sugar for bool foo = foo && bar and bool foo = foo || bar?
Is there a "very bad thing" that can happen &&= and ||= were used
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A
boolmay only betrueorfalsein C++. As such, using&=and|=is relatively safe (even though I don’t particularly like the notation). True, they will perform bit operations rather than logical operations (and thus they won’t short-circuit) but these bit operations follow a well-defined mapping, which is effectively equivalent to the logical operations, as long as both operands are of typebool.1Contrary to what other people have said here, a
boolin C++ must never have a different value such as2. When assigning that value to abool, it will be converted totrueas per the standard.The only way to get an invalid value into a
boolis by usingreinterpret_caston pointers:But since this code results in undefined behaviour anyway, we may safely ignore this potential problem in conforming C++ code.
1 Admittedly this is a rather big caveat as Angew’s comment illustrates:
The reason is that
b & 2performs integer promotion such that the expression is then equivalent tostatic_cast<int>(b) & 2, which results in0, which is then converted back into abool. So it’s true that the existence of anoperator &&=would improve type safety.