tags:

views:

121

answers:

3

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?

+5  A: 

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.

Starkey
+4  A: 
Prasoon Saurav
Is there a reference of sequence points I could use? You seem to know them all.
NullUserException
@NullUserException : Edited my answer in reponse to your comment.
Prasoon Saurav
+2  A: 

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.

AndreyT