confused by C++ logical OR (||) operator [duplicate] - c++

This question already has answers here:
Is Short Circuit Evaluation guaranteed In C++ as it is in Java?
(2 answers)
Closed 7 years ago.
Suppose I have two expressions left/right of || operator. I find if left expression is true, the right operator will never be called. For example, in my below code, when getRand returns true, I found Foo will never be called. I tested on XCode on Mac OSX, and wondering if it is a reliable feature of C++ we could rely on -- if left part of || is true, right part will never be called, or it is a special feature just for specific platform (e.g. OSX with XCode)? Post my code below, thanks.
bool Foo()
{
std::cout << "I am called!\n";
return false;
}
bool getRand()
{
int random_variable = std::rand();
std::cout << random_variable << '\n';
return random_variable % 2 == 1;
}
int main(int argc, const char * argv[]) {
if (getRand() || Foo())
{
std::cout<<"Hello World \n";
}
return 0;
}
thanks in advance,
Lin

Yes, it is a guaranteed feature called short circuit evaluation.
Likewise, an expression false && expression will never evaluate the right expression.

wondering if it is a reliable feature of C++ we could rely on -- if left part of || is true, right part will never be called?
Yes, for builtin operator.
From the standard, $5.15/1 Logical OR operator [expr.log.or] (bold by me)
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.
And note that the overload of operator|| will lose this special property.
Logical operators (bold by me)
Builtin operators && and || perform short-circuit evaluation (do not
evaluate the second operand if the result is known after evaluating
the first), but overloaded operators behave like regular function
calls and always evaluate both operands.

Since its one choice or another there is no need for the second part to be evaluated, is not platform dependant is a language feature.

Related

Has c++ standard specified the evaluation order of an operator&&(built-in)? [duplicate]

This question already has answers here:
Is short-circuiting logical operators mandated? And evaluation order?
(7 answers)
Closed 3 years ago.
I always dare NOT to code like this:
void func( some_struct* ptr ) {
if ( ptr != nullptr && ptr->errorno == 0 )
do something...
};
instead I always do like this:
void func( some_struct* ptr ) {
if ( ptr != nullptr )
if ( ptr->errorno == 0 )
do something...
};
because I'm afraid that the evaluation order of logical operator && is un-specified in C++ standard, even though commonly we could get right results with almost all of nowdays compilers.
In a book, 2 rules let me want to get known exactly about it.
My question is :
Without overloading, is the evaluation order of logical operator "&&" and "||" definite?
Sorry about my ugly English, I'm a Chinese. and I apologize if there is a duplicated topic, because I can't finger out correct key-words to search with.
Thanks anyway!
Yes, it's guaranteed for built-in logical AND operator and logical OR operator by the standard.
(emphasis mine)
[expr.log.and]/1
The && operator groups left-to-right. The operands are both contextually converted to bool. 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.
[expr.log.or]/1
The || operator groups left-to-right. The operands are both contextually converted to bool. The result is 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.
Evaluation order for && and || is left to right.
Means in this case if (condition-1 && condition-2), then compiler will first check condition-1. If condition-1 is true then it will go to check next condition. But if condition-1 if false. It will return false as in && one false condition means result is false
Sameway in case of if (condition-1 || condition-2), compiler will first check condition-1. If it is true then it will return true. Because if ||, if one condition is true, then result is true. No need to check next conditions. But if it is false it will check next condition...
Those operators have fixed evaluation rules that you can rely on.
You can safely use code like this:
if (op1 && op2)
With &&, both operands are needed to result to true in order for it to be true, if one of them is false then it short circuits, meaning that further evaluation of the && stops and it returns false. In short words, if the first operand is false then the second operand will not be evaluated since the operator will return false immediately.
For the case of || it will short circuit if at least one of its operands its true. Therefore, if the first operand is true then it will not evaluate the second operand because the operator returns true automatically.
This means that code like this: if (op1 && op2) is equivalent to:
if (op1)
{
if (op2)
{
//some code
}
}
And code like this if (op1 || op2) is the same as:
if (op1)
{
//some code
}
else if (op2)
{
//same code
}
Check these to know more about order of evaluation, operator precedence and logical operators.

In what order are expressions in an `if` condition evaluated? [duplicate]

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
}

Short-circuiting of non-booleans

Is it safe to shorten this usage of the ternary operator:
process_ptr(ptr ? ptr : default_ptr);
with the short-circuit:
process_ptr(ptr || default_ptr);
in C and C++? In other words, are we guaranteed to get either ptr or default_ptr back from the experssion, or is it perhaps allowed for the expression to result in an arbitrary "logical true" value, if the expression is logically true?
This is the kind of code you'd see all over Perl code, but I rarely see it in C/C++, that's the original basis of my question.
The second expression will evaluate to either 1 or 0.
Quoting the C11 standard draft:
6.5.14 Logical OR operator
The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.
So the two expressions are very different, since one of them yields a pointer, and the other one an integer.
Edit:
One of the comments claims that this answer is only valid for c, and #Lightness Races in Orbit is right.
There are also answers that are only correct for c++1, although the only difference with them is that c++ has type bool and then it evaluates this expression as bool instead of int. But apparently there is an important issue with overloading || operator in c++, which prvents short-citcuiting to apply for the object that overloads it.
So for c++ there are more things to consider, but since this question was tagged with both languages tags, then it's necessary to mention at least the differece.
The rule still applies when short-circuiting applies, i.e. the result of the evaluation of the expressions is either 1 or 0 for c and true or false for c++.
1 Like these answers: 1, 2
Concerning the Perl style, which usually is of type
do_someting || die("didn't work")
This would work in C++ also.
function_returning_bool(some) || std::cout << "Error!" << std::endl;
This is due to the || being a logical OR operator and causing the short-circuit in this case if the return value is true.
But using it instead of the ternary operator is impossible.
std::cout << ("asd" || "dsa");
This will result in 1 being output.
No. The result type is int (or bool in C++), and will be either 1 or 0 (true or false in C++).
operator|| for pointers returns a bool, so ptr || default_ptr will evaluate to true if either ptr or default_ptr are non-null.

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().

Does the order of operations change within an if expression?

I recently came across something that I thought I understood right off the bat, but thinking more on it I would like understanding on why it works the way it does.
Consider the code below. The (x-- == 9) is clearly getting evaluated, while the (y++ == 11) is not. My first thought was that logical && kicks in, sees that the expression has already become false, and kicks out before evaluating the second part of the expression.
The more I think about it, the more I don't understand why this behaves as it does. As I understand it, logical operators fall below increment operations in the order of precedence. Shouldn't (y++ == 11) be evaluated, even though the overall expression has already become false?
In other words, shouldn't the order of operations dictate that (y++ == 11) be evaluated before the if statement realizes the expression as a whole will be false?
#include <iostream>
using namespace std;
int main( int argc, char** argv )
{
int x = 10;
int y = 10;
if( (x-- == 9) && (y++ == 11) )
{
cout << "I better not get here!" << endl;
}
cout << "Final X: " << x << endl;
cout << "Final Y: " << y << endl;
return 0;
}
Output:
Final X: 9
Final Y: 10
logical operators fall below increment operations in the order of
precedence.
Order of precedence is not order of execution. They're completely different concepts. Order of precedence only affects order of execution to the extent that operands are evaluated before their operator, and order of precedence helps tell you what the operands are of each operator.
Short-circuiting operators are a partial exception even to the rule that operands are evaluated before the operator, since they evaluate the LHS, then the operator has its say whether or not to evaluate the RHS, maybe the RHS is evaluated, then the result of the operator is computed.
Do not think of higher-precedence operations "executing first". Think of them "binding tighter". ++ has higher precedence than &&, and in the expression x ++ && y ++, operator precedence means that the ++ "binds more tightly" to y than && does, and so the expression overall is equivalent to (x++) && (y++), not (x++ && y) ++.
Shouldn't (y++ == 11) be evaluated, even though the overall expression has already become false?
No: the && and || operators short-circuit: they are evaluated left-to-right and as soon as the result of the expression is known, evaluation stops (that is, as soon as the expression is known to be false in the case of a series of &&, or true in the case of a series of ||)(*).
There is no sense in doing extra work that doesn't need to be done. This short-circuiting behavior is also quite useful and enables the writing of terser code. For example, given a pointer to a struct-type object, you can test whether the pointer is null and then dereference the pointer in a subsequent subexpression, for example: if (p && p->is_set) { /* ... */ }.
(*) Note that in C++, you can overload both the && and the || for class-type operands and if you do, they lose their short-circuiting property (it is generally inadvisable to overload && and || for this reason).
Precedence and associativity do not specify the order in which the operations are actually performed. They specify how operations are grouped: that is, in the following expression:
x && y++
...the lower precedence of && says that it is grouped as if it was:
x && (y++)
rather than as
(x && y)++
In your expression, the relative precedence of && and ++ do not matter, because you have separated those operators with parentheses anyway.
Grouping (and therefore precedence and associativity) specify what value each operator is operating on; but it specifies nothing about when it does so.
For most operators, the order in which the operations are performed is unspecified - however, in the case of && it is specified to evaluate the left hand operand first, then only evaluate the right hand operand if the result of the left hand operand was non-zero.
No. Order of precedence simply decides whether you get this:
A && B
(with A being x-- == 9 and B being y++ == 11) or
A == B == C
(with A being x--, B being 9 && y++, and C being 11).
Obviously, we're dealing with the first case. Short circuiting fully applies; if A is true, then B is not evaluated.
The conditional operators evaluate left-to-right and stop as soon as the result is known (an AND with a falsity or an OR with a true value).
C standard does not dictate any particular order of expression evaluation in if. So behavior will be compiler specific and using this style of coding not portable. You face that problem because incrementing/decrementing of value is post operation, but standard says as post operation of expression where variable is used. So if a compiler considers that your expression is just single variable usage as x or y, then you will see one result. If a compiler thinks that expression is entire if expression evaluation, then you will see other result. I hope it helps.