In C have the following:
return (abc(1) || abc(2));
If abc(1 == 1)
returns true
will then call abc(2)
?
No, it won't. This is called "short-circuiting" and it is a common flow-control mechanism:
With a && b
, b
is only evaluated if a
is true; if a
is false, the whole expression must necessarily be false.
With a || b
, b
is only evaluated if a
is false; if a
is false, the whole expression may still be true.
No. It's guaranteed (by The Standard), that if abc(1)
returns true
, abc(2)
will NOT be called.
If abc(1)
returns false
, that it's guaranteed, that abc(2)
WILL be called.
It's similar with &&
: if you have abc(1) && abc(2)
, abc(2)
will be called ONLY IF abc(1)
return true
and will NOT be called, if abc(1)
return false
.
The idea behind this is:
true OR whatever -> true
false OR whatever -> whatever
false AND whatever -> false
true AND whatever -> whatever
This comes from the boolean algebra
If abc(1==1) returns true will then call abc(2) ?
No, it won't. This behavior is known as short-circuiting. It is guaranteed by C and C++ standards.
C11(n1570), § 6.5.13 Logical AND operator
Unlike the bitwise binary
&
operator, the&&
operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.
(Emphasis is mine.)
The same applies to the ||
operator.
||
(logical comparison) breaks further checking, while |
(bitwise comparison) doesn't.
You might also read: Difference between | and || or & and && for comparison
abc(2)
will be called only if abc(1)
is false
According to C99 specification, logical OR operator says
The || operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares unequal to 0, the second operand is not evaluated.
In C, the logical ||
operator is tested from left-to-right, guaranteed. For the whole statement to be true, either condition can be true. So ||
keeps going from left to right until one condition is true, and then stops (or it gets to the end). So no, if abc(1)
returns true then abc(2)
will not be called.
Contrast with &&
, which keeps going from left to right until one condition is false (or it gets to the end).
No. This is actually non trivial and defined in standard that logical operators are evaluated from left to right. Evaluation is stopped when the value can be determined with out further evaluation of operands. At least I am 100% sure for AND
and OR
.
This is non trivial problem, because therefore the evaluation of operands cannot be implicitly parallelized or optimized by reorganization of order, as the expected outcome could differ.
E.g. run-time troubles in wide-use cases such as if (*ptr && (ptr->number > other_number) )