Safe short circuit evaluation in C++11
Asked Answered
T

1

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?

Tetrachord answered 15/11, 2014 at 5:42 Comment(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.Heterozygote
C
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.

Carafe answered 15/11, 2014 at 5:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.