7

Pre-C++11 we know that short-circuiting and evaluation order are required for operator && because of:

1.9.18

In the evaluation of the following expressions

a && b
a || b
a ? b : c
a , b

using the built-in meaning of the operators in these expressions, there is a sequence point after the evaluation of the first expression (12).

But sequence points no longer exist in C++11, so where is the standard part that says:

if (ptr && ptr->do_something())
{
}

is safe?

  • 1
    Sequence points don't guarantee short-circuiting anyway. (Obviously `operator ,` can't possibly short circuit.) You still need the actual operator spec to guarantee that. – T.C. Nov 15 '14 at 11:19

1 Answers1

14

[expr.log.and]

The && operator groups left-to-right. The operands are both contextually converted to 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.

The result is a bool. If the second expression is evaluated, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second expression.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312