Safe short circuit evaluation in C++11

533 views Asked by At

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

There are 1 answers

0
Brian Bi On

[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.