#1,200 – Logical Operators vs. Conditional Logical Operators

You can use either the logical operators (|, &) or the conditional logical operators (||, &&) when comparing two boolean values (or expressions).

            bool isFromMN = true;
            bool likesConfrontation = false;

            bool bResult = likesConfrontation & isFromMN;  // false
            bResult = likesConfrontation && isFromMN;      // false
            bResult = likesConfrontation | isFromMN;       // true
            bResult = likesConfrontation || isFromMN;       // true

The difference between these operators, when used with boolean values, is that the conditional logical operators can short-circuit evaluation, avoiding evaluation of the right side of the expression if possible.

            int val = 0;

            // Short-circuits (right side not evaluated)
            bResult = isFromMN || ((5 / val) == 1);     // true 

            // Throws exception (does not short-circuit)
            bResult = isFromMN | ((5 / val) == 1);

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

4 Responses to #1,200 – Logical Operators vs. Conditional Logical Operators

  1. Pingback: Dew Drop – October 9, 2014 (#1873) | Morning Dew

  2. James Curran says:

    I’ve always been amazed by the number of professional programmers I’ve met who don’t understand short-circuit evaluation, despite the fact that it’s identical in C#, C++, Java Javascript and C, and thus has been that way for over 30 years (as part of the C language specification in K&R 1st Ed)

    And what I found truly stunning is many writers (thankfully, not you), assuming it’s just a quirk of a particular compiler and advocating not depending on it!

  3. Rinto Anto says:

    Short-circuiting often help me to avoid executing CPU intensive code when evaluating a logical expression which contains Lambda/Linq.

    bool flag = false;
    if( flag && )
    {

    }

Leave a comment