if( a < b && c < d )we don't bother evaluating the
c < d
part if a
is not less than b
since it doesn't matter
what c
and d
's relationship are; the condition is
false no matter what.
Similarly if we have
if( a < b || c < d )we don't need to evaluate
c < d
if a
is less than b
since the OR will be true
regardless of what c
and d
are.
The importance of this feature is not just that it avoids unnecessary computation. The main thing is that if the second part of such an expression has side effects, they won't always take place. For example,
if( a < b && f( a, b ))will only execute the function
f()
if a
is less than b
.
Unless you are intentionally taking advantage of the short-circuiting when usingWhat is the value of x after&&
or||
, don't put anything with side-effects on the right hand side.
x = 7 ; y = 15 ; if( x == 7 || y == x++ ) if( y == 15 && x < 8 ) x = 12 ; else x = 13 ; else if( x > y || y < 100 ) x = 14 ; else x = 15 ;