Why doesn't c++ have &&= or ||= for booleans?

前端 未结 3 689
醉酒成梦
醉酒成梦 2020-12-02 13:00

Is there a "very bad thing" that can happen &&= and ||= were used as syntactic sugar for bool foo = foo && bar

3条回答
  •  心在旅途
    2020-12-02 13:12

    A bool may only be true or false in 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 type bool.1

    Contrary to what other people have said here, a bool in C++ must never have a different value such as 2. When assigning that value to a bool, it will be converted to true as per the standard.

    The only way to get an invalid value into a bool is by using reinterpret_cast on pointers:

    int i = 2;
    bool b = *reinterpret_cast(&i);
    b |= true; // MAY yield 3 (but doesn’t on my PC!)
    

    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:

    bool b = true;
    b &= 2; // yields `false`.
    

    The reason is that b & 2 performs integer promotion such that the expression is then equivalent to static_cast(b) & 2, which results in 0, which is then converted back into a bool. So it’s true that the existence of an operator &&= would improve type safety.

提交回复
热议问题