19.3. Evaluation of Logical Expressions

[ fromfile: types.xml id: logical-exp ]

In C and C++, evaluation of a logical expression stops as soon as the logical value of the entire expression is determined. This shortcut mechanism may leave some operands unevaluated. The value of an expression of the form

     expr1 && expr2 && ... && exprn
    

is true if and only if all the operands are true. If one or more of the operands is false, the value of the expression is false. Evaluation of the expression proceeds sequentially, from left to right, and is guaranteed to stop (and return the value false) if it encounters an operand that has the value false.

Similarly, an expression of the form

     expr1 || expr2 || ... || exprn
     
    

is false if and only if all the operands are false. Evaluation of the expression proceeds sequentially, from left to right, and is guaranteed to stop (and return the value true) if it encounters an operand that has the value true.

Programmers often exploit this system with statements like

        if( x != 0 &&  y/x < z) {
        // do something ...
        }
        else {
        // do something else ...
        }
      

If x were equal to 0, evaluating the second expression would produce a runtime error. Fortunately that cannot happen.

Logical expressions often make use of both && and ||. It is important to remember that && has higher precedence than ||. In other words,

expr1 ||  expr2 &&  expr3
   

means

expr1 ||  (expr2 &&  expr3)
   

not

(expr1 ||  expr2) &&  expr3