Yes, because of short-circuit behavior of logical &&
operator, in case of &&
second expression evaluates only when first is true. Read following:
6.5.13 Logical AND operator
4 Unlike the bitwise binary &
operator, the &&
operator guarantees left-to-right
evaluation;
there is a sequence point after the evaluation of the first operand. If the first operand
compares equal to 0, the second operand is not evaluated.
From Is short-circuiting boolean operators mandated in C/C++? And evaluation order?
So if i > 0
is false (for example if i = 0
) then result of i > 0
expression will be false, and then second operand someFunc(arr[i-1], arr[i]
will not be called (evaluated).
Accordingly, if(i > 0 && someFunc(arr[i-1], arr[i]))
is safe to code, but be-careful i - 1
shouldn't be > max index value of arr[]
. Really I will prefer this form of if compare to nested if blocks (flat is better then nested).
From @Maroun Maroun's answer "Is there any reason for asking if(1 || Foo())
?" Additional information that might help you:
if(a && b)
- if a
is false
, b
won't be checked.
if(a && b)
- if a
is true
, b
will be checked, because if it's false
, the expression will be false
.
if(a || b)
- if a
is true
, b
won't be checked, because this is true
anyway.
if(a || b)
- if a
is false
, b
will be checked, because if b
is true
then it'll be true
.