Possible Duplicate:
Is short-circuiting boolean operators mandated in C/C++? And evaluation order?
Is there any defined by standard or math rules order of eveluating boolean sentences? For example:
if (firstTrue && secondTrue)
{
}
can I be sure that firstTrue will be checked first?
Yes firstTrue will be evaluated first. In fact, if firstTrue is false, the secondTrue will not even be evaluated. This is called short circuiting.
Check out this article: http://en.wikipedia.org/wiki/Short-circuit_evaluation
The same happens with ||
. If the first argument to ||
is true, the second will not be evaluated.
Yes. &&
and ||
are short circuiting operators. The order of evaluation of operands is well defined (left to right).
&&
is also a sequence point.
So writing if( ++i && i) { }
is perfectly fine.
ISO C++03 (5.14/1
) says:
The && operator groups left-to-right. The operands are both implicitly converted to type 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.
EDIT: (After seeing the comment)
ISO C++03 (Section 1.9/18
) says
In the evaluation of each of the expressions
a && b
a || b
a ? b : c
a , b using the built-in meaning of the operators in these expressions (5.14, 5.15, 5.16, 5.18), there is a sequence point after the evaluation of the first expression.
It is not about boolean sentences. It is about specific operators in these "sentences" (logical expressions, actually)
The built-in &&
operator (as well as ||
) are special: they guarantee that the left-hand side is evaluated before the right-hand size. They have a sequence point between the LHS and RHS evaluations. And they don't evaluate the RHS if the result is pre-determined by the LHS. Aside from this (and some other operators that have similar sequencing properties), there are no guarantees about the order of evaluation of logical expressions, or any other expressions.
The above applies to built-in &&
and ||
operators. Overloaded &&
and ||
operators are not special in any way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With