Search code examples
c++logical-operatorsoperator-precedenceexpression-evaluation

Has c++ standard specified the evaluation order of an operator&&(built-in)?


I always dare NOT to code like this:

void func( some_struct* ptr ) {
    if ( ptr != nullptr && ptr->errorno == 0 )
        do something...
};

instead I always do like this:

void func( some_struct* ptr ) {
    if ( ptr != nullptr )
        if ( ptr->errorno == 0 )
            do something...
};

because I'm afraid that the evaluation order of logical operator && is un-specified in C++ standard, even though commonly we could get right results with almost all of nowdays compilers. In a book, 2 rules let me want to get known exactly about it.

My question is : Without overloading, is the evaluation order of logical operator "&&" and "||" definite?

Sorry about my ugly English, I'm a Chinese. and I apologize if there is a duplicated topic, because I can't finger out correct key-words to search with. Thanks anyway!


Solution

  • Yes, it's guaranteed for built-in logical AND operator and logical OR operator by the standard.

    (emphasis mine)

    [expr.log.and]/1

    The && operator groups left-to-right. The operands are both contextually converted to bool. The result is true if both operands are true and false otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

    [expr.log.or]/1

    The || operator groups left-to-right. The operands are both contextually converted to bool. The result is true if either of its operands is true, and false otherwise. Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.