#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);
Advertisements