Search code examples
c++if-statementexecute

if conditions execute order in C++


I have a if block as below in C++:

if( node != NULL && node->next !=NULL ){
    //do some stuff
}

Can anybody tell me do I need to split node and node->next in two if block? or is it guaranteed that node!=NULL will executed before node->next!=NULL ?


Solution

  • This is a short circuit evaluation and the operator && guarantees that the left-hand side expression will be fully evaluated before the right-hand side is evaluated

    From the standards:

    5.14 Logical AND operator [expr.log.and]

    logical-and-expression: 
          inclusive-or-expression
          logical-and-expression && inclusive-or-expression 
    
    1. The && operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). 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.
    2. The result is a bool. If the second expression is evaluated, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second expression.