C and C++ operand resolution order - c++

Many times I see (and sometimes write) code similar to this example:
int a=0, b=2;
if( a && (b=func())!=0 ) {
//...
The question is: does the standard guarantee these statements?
b will be not touched (and remain value 2)
func() will not be called
And vice-versa, if we write if( func()!=0 && a ) - does the standard guarantee func() will be called?
I'm interested in the particular standard paragraph defining this is legitimate.
UPD: my typo, changed from int a=1 to int a=0

To the exact question;
The question is: does standard guarantee these statements?
To the updated question; given a=0. If a==0, then yes, the short circuit evaluation would kick in and func() would not be called; the second operand would not be evaluated.
If a=1 (as it was originally), the opposite; func() will be called - a is 1 thus "true", as a result the second operand is evaluated (it is a logical AND), b will change. If the operator had been || (logical OR), then short circuit evaluation would kick in and func() would not be called.
And vice-versa, if we write if( func()!=0 && a ) -- does standard guarantee func() will be called?
Yes, the first operand is always evaluated.
Yes, short circuit evaluation is guaranteed for C++;
§5.14 Logical AND operator
1 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.
2 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.
§5.15 Logical OR operator
1 The || operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). It returns true if either of its operands is true, and false otherwise. Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.
2 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.
The corresponding quotes for C are;
§6.5.13 Logical AND operator
4 Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.
§6.5.14 Logical OR operator
4 Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.

From the C-90 standard.
6.5.13 Logical AND operator
....
4 Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation;
there is a sequence point after the evaluation of the first operand. If the first operand
compares equal to 0, the second operand is not evaluated.
Similarly for the Logical OR operator.

The && operator requires both operands to be true. If the first operand evaluates to false, then the second operand will not be evaluated. But beause a is 1, it is considered true and the second expression (operand) is evaluated. Thus func() is called and its result assigned to b and then b is tested to be non-zero.

The standard guarantees that the statements in a sequence of && are evaluated from left to right, and that as soon as one of them evaluates to false, the ones to the right of that will not be evaluated.

The question is: does standard guarantee these statements?
b will be not touched (and remain value 2)
func() will not be called
No, in fact both of them wrong in this case. Because it's operator && so no shortcut logic can be applied in this particular case.
If you change it to || then your statements are correct - only then the evaluation of the first operand (a = 1 in this case) will be enough and the rest is ignored.
As the question changed to a = 0 then yes, both statements are correct and guaranteed.

Related

Is short-circuit evaluation safe in my case?

I have a simple condition that looks like this :
if (k==0 && f())
f has side effects and must not be called if k is different from 0. Can I rely on boolean short-circuits so that the compiler never calls f ? Of course, I could haved moved the if to the outside to guarantee f is never called when k != 0, but this is shorter.
8.14 Logical AND operator [expr.log.and]
The && operator groups left-to-right. The operands are both contextually converted to bool (Clause 7). 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.
So, if k is not equal to 0, a conformant compiler will not call f.

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

if conditions execute order in C++

I have a if block as below in C++:
if( node != NULL && node->next !=NULL ){
//do some stuff
}
Can anybody tell me do I need to split node and node->next in two if block? or is it
guaranteed that node!=NULL will executed before node->next!=NULL ?
This is a short circuit evaluation and the operator && guarantees that the left-hand side expression will be fully evaluated before the right-hand side is evaluated
From the standards:
5.14 Logical AND operator [expr.log.and]
logical-and-expression:
inclusive-or-expression
logical-and-expression && inclusive-or-expression
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.
No, you do not. The && operator short-circuits; if the left operand evaluates to false then the right operand is not evaluated at all, because the result is already known. (Similarly, the || operator will not evaluate the right operand when the left operand is true.)
You do not need to. node!=NULL will execute first and if it is false it will not evaluate the rest of the conditions.
If the first condition is false then the second condition will not be evaluated because in any case the full expression will be equal to false independing on what is the result of evaluatuin of the second condition.
According to the C++ Standard
1 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.

Sequence point && operator

For C++03, the standard says, that between left and right operand of && operator there is a sequence point, so that all side effects of left operator have taken place before right operator is accessed.
So
int i = 0;
if (++i && i--)
std::cout << i;
is well defined and is guaranteed to output 0.
But what is about this question: is right operand only evaluated if left operand is not 0? It seems to be a detail, but to me the standard guarantees only the sequence point between the operands, not that right operand is never evaluated/accessed in dependence of left one.
E.g.
int arr[10];
int pos; // somehow set to a value from 0 to 10
while (pos < 10 && arr[pos] != 0)
pos++;
Is this well defined? pos could be from begin on 10 or reaches 10. The left operand has no side effects which concur with right operand. Have I the guarantee that arr[10] != 0 is never performed?
Edit:
Thanks to the comments and answers it is clear now:
5.14p2: "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."
is the sequence point meaning.
5.14p1: "Unlike &, && guarantees left-to-right evaluation: the second operand is
not evaluated if the first operand is false."
is the short-circuit meaning.
The first without the second would make my example undefined. Thanks.
The standard does guarantee short-circuiting of && and ||.
If the left-hand side of && is false, the right-hand side is not evaluated. For ||, the right-hand side is not evaluated if the left-hand side is true.
5.14p1 of C++11, last sentence:
Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.
So yes, it's guaranteed.

"IF" argument evaluation order?

if(a && b)
{
do something;
}
is there any possibility to evaluate arguments from right to left(b -> a)?
if "yes", what influences the evaluation order?
(i'm using VS2008)
With C++ there are only a few operators that guarantee the evaluation order
operator && evaluates left operand first and if the value is logically false then it avoids evaluating the right operand. Typical use is for example if (x > 0 && k/x < limit) ... that avoids division by zero problems.
operator || evaluates left operand first and if the value is logically true then it avoids evaluating the right operand. For example if (overwrite_files || confirm("File existing, overwrite?")) ... will not ask confirmation when the flag overwrite_files is set.
operator , evaluates left operand first and then right operand anyway, returning the value of right operand. This operator is not used very often. Note that commas between parameters in a function call are not comma operators and the order of evaluation is not guaranteed.
The ternary operator x?y:z evaluates x first, and then depending on the logical value of the result evaluates either only y or only z.
For all other operators the order of evaluation is not specified.
The situation is actually worse because it's not that the order is not specified, but that there is not even an "order" for the expression at all, and for example in
std::cout << f() << g() << x(k(), h());
it's possible that functions will be called in the order h-g-k-x-f (this is a bit disturbing because the mental model of << operator conveys somehow the idea of sequentiality but in reality respects the sequence only in the order results are put on the stream and not in the order the results are computed).
Obviously the value dependencies in the expression may introduce some order guarantee; for example in the above expression it's guaranteed that both k() and h() will be called before x(...) because the return values from both are needed to call x (C++ is not lazy).
Note also that the guarantees for &&, || and , are valid only for predefined operators. If you overload those operators for your types they will be in that case like normal function calls and the order of evaluation of the operands will be unspecified.
Changes since C++17
C++17 introduced some extra ad-hoc specific guarantees about evaluation order (for example in the left-shift operator <<). For all the details see https://stackoverflow.com/a/38501596/320726
The evaluation order is specified by the standard and is left-to-right. The left-most expression will always be evaluated first with the && clause.
If you want b to be evaluated first:
if(b && a)
{
//do something
}
If both arguments are methods and you want both of them to be evaluated regardless of their result:
bool rb = b();
bool ra = a();
if ( ra && rb )
{
//do something
}
In this case, since you're using &&, a will always be evaluated first because the result is used to determine whether or not to short-circuit the expression.
If a returns false, then b is not allowed to evaluate at all.
Every value computation and side effect of the first (left) argument of the built-in logical AND operator && and the built-in logical OR operator || is sequenced before every value computation and side effect of the second (right) argument.
Read here for a more exhaustive explanation of the rules set:
order evaluation
It will evaluate from left to right and short-circuit the evaluation if it can (e.g. if a evaluates to false it won't evaluate b).
If you care about the order they are evaluated in you just need to specify them in the desired order of evaluation in your if statement.
The built-in && operator always evaluates its left operand first. For example:
if (a && b)
{
//block of code
}
If a is false, then b will not be evaluated.
If you want b to be evaluated first, and a only if b is true, simply write the expression the other way around:
if (b && a)
{
//block of code
}