Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the order of evaluating boolean sentence? [duplicate]

Tags:

c++

boolean

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?

like image 320
There is nothing we can do Avatar asked Sep 25 '10 15:09

There is nothing we can do


3 Answers

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.

like image 149
Starkey Avatar answered Oct 24 '22 13:10

Starkey


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.

  • like image 34
    Prasoon Saurav Avatar answered Oct 24 '22 12:10

    Prasoon Saurav


    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.

    like image 40
    AnT Avatar answered Oct 24 '22 13:10

    AnT