OR Statement performing all evaluations [duplicate] - c++

This question already has answers here:
Is short-circuiting logical operators mandated? And evaluation order?
(7 answers)
Closed 3 years ago.
In an OR evaluation does C++ continue evaluating past the first TRUE it finds?
ie.
if(Foo() || Bar())
{
//..
}
If Foo() returns true will Bar() be skipped completely or will it also run that function?

Operators && and || perform so called short-circuit evaluation, which means they do not evaluate the second operand if the result is known after evaluating the first. So no, Bar() would not be evaluated in this case.
EDIT: That's the built-in functionality, as other people said. If they are overloaded, you obviously can't rely on it anymore.

The built-in || operator short-circuits. The left-hand expression is guaranteed to be evaluated first, and if the result is true, the right-hand expression is not evaluated.
The && operator is the opposite. The left-hand expression is evaluated first and if it evaluates to false then the right-hand expression is not evaluated.
Note that this does not hold for user-defined operator|| and operator&& overloads. Those do not provide short-circuit evaluation. Both sides of the expression will be evaluated.

Related

Is if statement order check fr object depend on compiler? [duplicate]

This question already has an answer here:
Logical AND, OR: Is left-to-right evaluation guaranteed?
(1 answer)
Closed 5 years ago.
Quick question. How the following code will perform order of check :
if ((NULL != ObjectPtr) && (ObjectPtr->isValid()) )
{
}
Is the order on if-statement depend on compiler used? Could that code crash if ObjectPtr is NULL?
Is the order depend on if statement depend on compiler used?
No.
Could that code crash if ObjectPtr is NULL?
No.
The language guarantees that.
In C++, the && operator is guaranteed to be short-circuiting. This means that the left-hand operand is checked first, and if it is false, none of the right-hand operand is evaluated.
So your code is safe and will not perform member access through the NULL pointer.
Similarly, || is also short-circuiting and will not evaluate any of its right-hand operand if the left operand is true.
With boolean operands, the bitwise operators & and | give the same result as the logical operators && and ||, but the bitwise operators do not short-circuit and their right-hand operand is always evaluated (possibly before the left-hand one).
Also as Quentin mentions in a comment, user-provided overloads of these operators do not short-circuit, because they are actually function calls and have the evaluation order of function calls (all arguments evaluated before the call).

Is an if statement guaranteed to not be evaluated more than necessary? [duplicate]

This question already has answers here:
Is short-circuiting logical operators mandated? And evaluation order?
(7 answers)
How does C++ handle &&? (Short-circuit evaluation) [duplicate]
(7 answers)
Closed 9 years ago.
Given two conditions with an && connection. I know that the order of evaluation is from left to right. But if the first condition resolves to false, it the second condition guaranteed to not get evaluated?
#define SIZE
bool array[SIZE];
int index;
// play with variables
// ...
if(index < SIZE && array[index])
{
// ...
}
In this example, if the first condition is false the second must not be evaluated since the access in the array would be out of range.
By the way I cannot simply nest the conditionals with two if statements, since actually I need the inverse like (!(in_range && get_element)). With nested statements I would need to use goto to jump over the code block below that.
But if the first condition resolves to false, it the second condition guaranteed to not get evaluated?
Yes, that's C++'s short circuiting. Per paragraph 5.14/1 of the C++11 Standard:
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.
As MatthieuM. correctly mentions in the comments, the above applies only to the built-in logical AND and logical OR operators: if those operators are overloaded, invoking them is treated as a regular function call (so no short-circuiting applies and no order of evaluation is guaranteed).
As specified in paragraph 5/2:
[Note: Operators can be overloaded, that is, given meaning when applied to expressions of class type (Clause
9) or enumeration type (7.2). Uses of overloaded operators are transformed into function calls as described
in 13.5. Overloaded operators obey the rules for syntax specified in Clause 5, but the requirements of
operand type, value category, and evaluation order are replaced by the rules for function call. [...] —end note ]

Will my compiler reorder this expression? [duplicate]

This question already has answers here:
Is Short Circuit Evaluation guaranteed In C++ as it is in Java?
(2 answers)
Closed 9 years ago.
If I write:
if(somePtr != NULL && somePtr->someFun() == SUCCESS )
{
/**/
}
Will it be assured that somePtr != NULL will be checked before somePtr->someFun() == SUCCESS?
Is there any chance that my compiler will reorder these two?
Is there any chance that my compiler will reorder these two?
Nope. It is guaranteed that && evaluates the second expression only if the first one is true (incidentally, it also introduces a sequence point into the whole expression).
The && operator groups left-to-right. The operands are both contextually converted to type 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.
(C++11, [expr.log.and]; emphasis added)

C++ 'AND' evaluation - standard guaranteed? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Safety concerns about short circuit evaluation
What does the standard say about evaluating && expressions - does it guarantee that evaluation of parameters will stop at the first false?
E.g.:
Foo* p;
//....
if ( p && p->f() )
{
//do something
}
is the f() guaranteed not to be called if p == NULL?
Also, is the order of evaluation guaranteed to be the order of appearence in the clause?
Might the optimizer change something like:
int x;
Foo* p;
//...
if ( p->doSomethingReallyExpensive() && x == 3 )
{
//....
}
to a form where it evaluates x==3 first? Or will it always execute the really expensive function first?
I know that on most compilers (probably all) evaluation stops after the first false is encountered, but what does the standard say about it?
What does the standard say about evaluating && expressions - does it guarantee that evaluation of parameters will stop at the first false?
Yes. That is called short-circuiting.
Also, is the order of evaluation guaranteed to be the order of appearence in the clause?
Yes. From left to right. The operand before which the expression short-circuited doesn't get evaluated.
int a = 0;
int b = 10;
if ( a != 0 && (b=100)) {}
cout << b << endl; //prints 10, not 100
In fact, the above two points are the keypoint in my solution here:
Find maximum of three number in C without using conditional statement and ternary operator
In the ANSI C standard 3.3.13:
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.
There is an equivalent statement in the C++ standard
&& (and ||) establish sequence points. So the expression on the left-hand side will get evaluated before the right-hand side. Also, yes, if the left-hand side is false/true (for &&/||), the right-hand side is not evaluated.
What does the standard say about evaluating && expressions - does it guarantee that evaluation of parameters will stop at the first false?
Also, is the order of evaluation guaranteed to be the order of appearence in the clause?
5.14/1. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.
This only works for the standard && operator, user defined overloads of operator && don't have this guarantee, they behave like regular function call semantics.
Might the optimizer change something like:
if ( p->doSomethingReallyExpensive() && x == 3 )
to a form where it evaluates x==3 first?
An optimizer may decide to evaluate x == 3 first since it is an expression with no side-effects associated if x is not modified by p->doSomethingReallyExpensive(), or even evaluate it after p->doSomethingReallyExpensive() already returned false. However, the visible behavior is guaranteed to be the previously specified: Left to right evaluation and short-circuit. That means that while x == 3 may be evaluated first and return false the implementation still has to evaluate p->doSomethingReallyExpensive().

What is the order of evaluating boolean sentence? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Is short-circuiting boolean operators mandated in C/C++? And evaluation order?
Is there any defined by standard or math rules order of eveluating boolean sentences? For example:
if (firstTrue && secondTrue)
{
}
can I be sure that firstTrue will be checked first?
Yes. && and || are short circuiting operators. The order of evaluation of operands is well defined (left to right).
&& is also a sequence point.
So writing if( ++i && i) { } is perfectly fine.
ISO C++03 (5.14/1) says:
The && operator groups left-to-right. The operands are both implicitly converted to type 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.
EDIT: (After seeing the comment)
ISO C++03 (Section 1.9/18) says
In the evaluation of each of the expressions
a && b
a || b
a ? b : c
a , b
using the built-in meaning of the operators in these expressions (5.14, 5.15, 5.16, 5.18), there is a sequence point after the evaluation of the first expression.
Yes firstTrue will be evaluated first. In fact, if firstTrue is false, the secondTrue will not even be evaluated. This is called short circuiting.
Check out this article: http://en.wikipedia.org/wiki/Short-circuit_evaluation
The same happens with ||. If the first argument to || is true, the second will not be evaluated.
It is not about boolean sentences. It is about specific operators in these "sentences" (logical expressions, actually)
The built-in && operator (as well as ||) are special: they guarantee that the left-hand side is evaluated before the right-hand size. They have a sequence point between the LHS and RHS evaluations. And they don't evaluate the RHS if the result is pre-determined by the LHS. Aside from this (and some other operators that have similar sequencing properties), there are no guarantees about the order of evaluation of logical expressions, or any other expressions.
The above applies to built-in && and || operators. Overloaded && and || operators are not special in any way.