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

前端 未结 3 670
醉酒成梦
醉酒成梦 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<bool*>(&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<int>(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.

    0 讨论(0)
  • 2020-12-02 13:20

    Short answer

    All the operators +=, -=, *=, /=, &=, |=... are arithmetic and provide same expectation:

    x &= foo()  // We expect foo() be called whatever the value of x
    

    However, operators &&= and ||= would be logical, and these operators might be error-prone because many developers would expect foo() be always called in x &&= foo().

    bool x;
    // ...
    x &&= foo();           // Many developers might be confused
    x = x && foo();        // Still confusing but correct
    x = x ? foo() : x;     // Understandable
    x = x ? foo() : false; // Understandable
    if (x) x = foo();      // Obvious
    
    • Do we really need to make C/C++ even more complex to get a shortcut for x = x && foo()?

    • Do we really want to obfuscate more the cryptic statement x = x && foo()?
      Or do we want to write meaningful code like if (x) x = foo();?


    Long answer

    Example for &&=

    If &&= operator was available, then this code:

    bool ok = true; //becomes false when at least a function returns false
    ok &&= f1();
    ok &&= f2(); //we may expect f2() is called whatever the f1() returned value
    

    is equivalent to:

    bool ok = true;
    if (ok) ok = f1();
    if (ok) ok = f2(); //f2() is called only when f1() returns true
    

    This first code is error-prone because many developers would think f2() is always called whatever the f1() returned value. It is like writing bool ok = f1() && f2(); where f2() is called only when f1() returns true.

    • If the developer actually wants f2() to be called only when f1() returns true, therefore the second code above is less error-prone.
    • Else (the developer wants f2() to be always called), &= is sufficient:

    Example for &=

    bool ok = true;
    ok &= f1();
    ok &= f2(); //f2() always called whatever the f1() returned value
    

    Moreover, it is easier for compiler to optimize this above code than that below one:

    bool ok = true;
    if (!f1())  ok = false;
    if (!f2())  ok = false;  //f2() always called
    

    Compare && and &

    We may wonder whether the operators && and & give the same result when applied on bool values?

    Let's check using the following C++ code:

    #include <iostream>
    
    void test (int testnumber, bool a, bool b)
    {
       std::cout << testnumber <<") a="<< a <<" and b="<< b <<"\n"
                    "a && b = "<< (a && b)  <<"\n"
                    "a &  b = "<< (a &  b)  <<"\n"
                    "======================"  "\n";
    }
    
    int main ()
    {
        test (1, true,  true);
        test (2, true,  false);
        test (3, false, false);
        test (4, false, true);
    }
    

    Output:

    1) a=1 and b=1
    a && b = 1
    a &  b = 1
    ======================
    2) a=1 and b=0
    a && b = 0
    a &  b = 0
    ======================
    3) a=0 and b=0
    a && b = 0
    a &  b = 0
    ======================
    4) a=0 and b=1
    a && b = 0
    a &  b = 0
    ======================
    

    Conclusion

    Therefore YES we can replace && by & for bool values ;-)
    So better use &= instead of &&=.
    We can consider &&= as useless for booleans.

    Same for ||=

    operator |= is also less error-prone than ||=

    If a developer wants f2() be called only when f1() returns false, instead of:

    bool ok = false;
    ok ||= f1();
    ok ||= f2(); //f2() is called only when f1() returns false
    ok ||= f3(); //f3() is called only when f1() or f2() return false
    ok ||= f4(); //f4() is called only when ...
    

    I advice the following more understandable alternative:

    bool ok = false;
    if (!ok) ok = f1();
    if (!ok) ok = f2();
    if (!ok) ok = f3();
    if (!ok) ok = f4();
    // no comment required here (code is enough understandable)
    

    or if you prefer all in one line style:

    // this comment is required to explain to developers that 
    // f2() is called only when f1() returns false, and so on...
    bool ok = f1() || f2() || f3() || f4();
    
    0 讨论(0)
  • 2020-12-02 13:30

    && and & have different semantics: && will not evaluate the second operand if the first operand is false. i.e. something like

    flag = (ptr != NULL) && (ptr->member > 3);
    

    is safe, but

    flag = (ptr != NULL) & (ptr->member > 3);
    

    is not, although both operands are of type bool.

    The same is true for &= and |=:

    flag = CheckFileExists();
    flag = flag && CheckFileReadable();
    flag = flag && CheckFileContents();
    

    will behave differently than:

    flag = CheckFileExists();
    flag &= CheckFileReadable();
    flag &= CheckFileContents();
    
    0 讨论(0)
提交回复
热议问题