Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe short circuit evaluation in C++11

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?

like image 563
user4254894 Avatar asked Nov 15 '14 05:11

user4254894


1 Answers

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

like image 50
Brian Bi Avatar answered Oct 13 '22 21:10

Brian Bi