Search code examples
c#boolean-logicshort-circuiting

Does combining short-circuiting operators with regular operators change the result of the expression?


I've always believed that using conditional boolean operators (a.k.a. short-circuiting) in stead of regular boolean operators doesn't affect the outcome of an expression.

var result = true | false & false;

has the same result as

var result = true || false && false

Both expressions result in true.

But what if I would mix regular and conditional operators?

var result1 = true || false & false;
var result2 = true | false && false;

What would you expect? I would expect these to still return true. But that isn't the case. Result2 will be false!

I know this is because of the operator precedence. The precedence order is & | && ||. This seems counter intuitive to me. I'd expect an order of & && | ||, in which case all results would be the same (I think).

So I guess my real question isn't if short-circuiting can change the result. The question is why the order of precedence is such that short-circuiting can change the result.


Solution

  • var result2 = true | false && false;
    

    Is calculated as:

    var result2 = (true | false) && false;
    

    Because | comes before &&. Now (true | false) evaluates to true, and true && false is false.

    As for the why, see this question:

    The && and || operators were added later for their "short-circuiting" behavior. Dennis Ritchie admits in retrospect that the precedence of the bitwise operators should have been changed when the logical operators were added. But with several hundred kilobytes of C source code in existence at that point and an installed base of three computers, Dennis thought it would be too big of a change in the C language...