3

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 ?

Jaden
  • 45
  • 7
  • 3
    You don't need to split it. short-circuit eval will prevail and avoid the secondary expression if the first is already deemed false. – WhozCraig Sep 04 '14 at 18:50
  • node!=NULL will always get executed before node->next!=NULL – Donal Sep 04 '14 at 18:51
  • As long as `operator&&` has not been overloaded for your type (which in this case is the result of `operator!=` which is a `bool` so you can trust that `operator&&` hasn't been overloaded) it will short circuit and work as expected. If someone has overloaded `operator&&` it loses the ability to short circuit. – YoungJohn Sep 04 '14 at 19:05

4 Answers4

15

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.
Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

No, you do not. The && operator short-circuits; if the left operand evaluates to false then the right operand is not evaluated at all, because the result is already known. (Similarly, the || operator will not evaluate the right operand when the left operand is true.)

cdhowie
  • 158,093
  • 24
  • 286
  • 300
0

You do not need to. node!=NULL will execute first and if it is false it will not evaluate the rest of the conditions.

RockOnRockOut
  • 751
  • 7
  • 18
0

If the first condition is false then the second condition will not be evaluated because in any case the full expression will be equal to false independing on what is the result of evaluatuin of the second condition.

According to the C++ Standard

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335