What is the order of evaluating boolean sentence?

13,238

Solution 1

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.

  • Solution 2

    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.

    Solution 3

    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.

    Share:
    13,238
    There is nothing we can do
    Author by

    There is nothing we can do

    In total love with C++.

    Updated on June 13, 2022

    Comments

    • There is nothing we can do
      There is nothing we can do almost 2 years

      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?

    • NullUserException
      NullUserException over 13 years
      Is there a reference of sequence points I could use? You seem to know them all.
    • Prasoon Saurav
      Prasoon Saurav over 13 years
      @NullUserException : Edited my answer in reponse to your comment.