Execution direction of && Condition [duplicate] - c++

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Logical comparisons: Is left-to-right evaluation guaranteed?
I have been taught that for every C function arguments, Rightmost argument will be executed/processed first and it progresses towards left.
Right part will be executed first and it progresses towards left.
Is this applicable to conditions like && and || ??
If I am writing a C++ Code, I check for NULL condtion first and then in next if I perform my action. for e.g.
if( CommDevice != NULL)
{
if(CommDevice->isOpen == TRUE)
{
//Do Something
}
}
Can I convert this in if((CommDevice != NULL) && (CommDevice->isOpen == TRUE) )
That "Code executes from Right to Left" fear is stopping me coz what if CommDevice is NULL and I am trying to access a member of NULL. It will generate exception.

I have been taught that every C function takes argument from right to left. Right part will be executed first and it progresses towards left.
This is 100% not true. The order of argument evaluation is unspecified!
The order of && and || is defined because it forms a sequence point. First the left is evaluated, and if not short-circuiting then the right is evaluated.
if((CommDevice != NULL) && (CommDevice->isOpen == TRUE) )
This is correct.

From the "C Programming Language" by Brian Kernighan & Ritchie Dennis (authors of C):
"Expressions connected by && or || are evaluated left to right, and it is guaranteed that evaluation will stop as soon as the truth or falsehood is known."
I should point out that I once confused the order of evaluation rules for && and || with the following in C:
x = f() + g();
Note that order of evaluation for f() vs. g() CANNOT be determined.

&& evaluates from left to right, not right to left! So your code will NOT throw any exception.

Order of evaluation of functions arguments is Unspecified .So whatever you have been taught is not according to language standard.
Regarding your code :
The order of evaluation of && and || is specified and this is Left to right
And this also follows the short-circuit of statement
In case of && if 1st is false then rest of the conditions will not be executed.
Similar in || if 1st is true then rest of the conditions will not be executed.
And also && and || are sequence points.

As far as the logical operators are concerned, you're touching on short-circuit evaluation.
It is safe to check for the NULL pointer first on the left, because if this condition returns false, then the next condition of the && (from left to right) is not evaluated.
This behavior is allowed because of the basic logical principles of && and ||.

Related

Checking container size in same "if" statement as reading from it

Let's say I have a vector of unknown length.
I want to check if there is a value at vector[3] that is equal to x.
I have to first check if the vector has a length of at least 4.
if(vector.length()>=4)
{
if(vector.at(3) == x)
// Do something
}
My question is: Is it correct to write the same code like this:
if(vector.length()>=4 && vector.at(3) == x)
// Do something
?
Yes, these are equivalent.
The logical AND operator && has what is referred to as short circuit behavior. If the left operand evaluates to false (i.e. 0) then the entire expression is false and the right operand is not evaluated.

precedence of () is not greater than &&

In the following code,
int main() {
int a =1, b = 2, c = 3;
if(((a++) == 5) && ((b++) == 5) && ((c++) == 5)) {
cout<<"inside if"<< endl; // prints !!!Hello World!!!
}
cout<<a<<b<<c<<endl;
return 0;
}
all increment operation should be done before doing logical operation. But execution skips increment b and c. Why logical && precede over ()? By the way, result of this code is 223.
Because of short circuiting: when the left hand side of && is false, the right-hand side is not evaluated. The precedence, on the other hand, is the way you think it should be (and, as AnT says, it's unrelated to the behavior you're seeing): () has precedence over &&.
(Similarly, when the left hand side of || is true, the right-hand side is not evaluated.)
all increment operation should be done before doing logical operation
This is simply not true. There's no reason why increment operation should be done before doing logical operation and () does not change that in any way. As it has been stated many times before, operator precedence does not have anything to do with order of evaluation. These are two completely unrelated concepts.
At the top level, your expression has the following structure
<term1> && <term2> && <term3> && ... && <termN>
Such expressions are always evaluated in strictly sequenced left-to-right order from <term1> to <termN> (with possibly short-circuited evaluation). It is completely irrelevant what you have inside those terms: nothing inside <term2> will ever be evaluated before <term1>.

Short circuit recursion

Is it possible to do the following without getting a stackoverflow?
int foo(int i = 0)
{
return foo(--i) || i;
}
When foo(--i) evaluates to 0, it should return false, therefore returning i and ending the execution.
You want return !i || foo(--i).
Note that || is short-circutted. This means that evaluation (which is performed from left to right) will continue for only as long as the result of the expression is not known. So the way I've written it, the case i being zero will block the recursion.
(Moving on to more advanced issues, you need to be very careful when evaluating expressions when the same variable appears in more than one sub-expression and it's value is changed in some of them. My having !i and --i could get me in trouble: I'm not too far away from undefined behaviour here. In fact, it turns out that my code is completely safe since || is a sequence point and the order of evaluation with || is well-defined. But do be careful.)
From what you have coded foo never returns because it will continuosly go on decreasing i and recurse. You need a check inside foo which returns whatever you want when you get i as 0.

What's the point of the NOT operator? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Currently checking out C++ using this tutorial. It explains what the ! NOT operator is, kind of, but I don't think I fully understand why I'd ever want to use it. Can someone please explain?
The ! operator is useful if you want to check that a condition is not currently satisfied.
Imagine a function that tells you if a particular subsystem of your application was initialized and another function to initialize it:
bool subsystem_is_initialized();
void subsystem_initialize();
You could check that it was initialized and initialize it if it wasn't using the not operator.
if (!subsystem_is_initialized())
subsystem_initialize();
For all practical purposes, it's a shorter way to compare a value to zero, with an explicit suggestion that the affected value is boolean. You don't absolutely need it, but then again, neither do you need multiplications (you can loop over an addition), additions (you can do it with binary logic), or most of binary logic (you can do pretty much anything with NANDs, I've been told, but I haven't researched it myself).
Also keep in mind that, like almost all other C++ operators, it can be overloaded by classes.
A language is not always (in fact as good as never) defined to have the minimal set of features but a set of features that useful. For example, if you had the following code:
if (!test_something())
do_something();
You could also express this as
if (test_something()) {
} else
do_something();
but it would be less easy to read. So, while logical negation can usually be expressed by other constructs of the C++ language, it helps readability to express negation explicitly to indicate your intent.
It's used when you need to flip a true/false in a condition, to increase readability.
e.g.
Compare
// Ensure that the thing is NOT red.
if (thing_is_red() == false)
...
if (!thing_is_red())
...
Okay, you want to divide the sum of two numbers to a third one, so you can do this if the third number is not zero.
#include <iostream>
using namespace std;
int main()
{
int a,b,c,sum;
cin >> a >> b >> c;
sum = a+b;
if (c!=0) //which is equivalent to if(!c)
cout << sum/c;
}
I used an easy example in order to understand it quickly. Is everything okay now? Regards and good luck with your study.
! or the NOT operator is the logical equivalent of a NOT gate.
So, a NOT gate truth table says if x is true, then !x is false. and vice-versa.
Not too difficult if you think of it logically. For example NOT of male is a female, NOT true is false, NOT simple is complex..
The most frequent case is probably with an std::istream:
int i;
std::cin >> i;
if ( ! std::cin ) {
// Something went wrong...
}
Other than that, all sorts of classes have isValid() or
isDone() functions; to iterate using a GoF iterator, for
example:
for ( IteratorType i( init ); ! i.isDone(); i.next() ) {
// Do something with i.element()
}
Map classes often have a contains function, so you might ask
if ( ! myMap.contains( key ) )
You'll also use boolean variables from time to time: for
a linear search where the match condition requires some
complicated evaluation, for example:
bool found = false;
int current = 0;
while ( ! found && current != end ) {
// maybe set found...
}
The tutorial you mention:
NOT: The NOT operator accepts one input. If that input is TRUE, it returns FALSE, and if that input is FALSE, it returns TRUE.
it means NOT operator is unary operator means single operand(not a binary operator)
like && and||` are binary operators and there syntax is:
result = operand1 && operand2
result = operand1 || operand2
Unary is:
result = !operand1
and its result values is revert of operand value id operand1 = True then result would be False and if operand1 = False result is True.
same is written there:
For example, NOT (1) evaluates to 0, and NOT (0) evaluates to 1. NOT (any number but zero) evaluates to 0. In C and C++ NOT is written as !. NOT is evaluated prior to both AND and OR.
in c/c++ 0 is False and
Non 0 is equivalent to True.
there is couple of good examples too!
(1).
!( 1 || 0 )
We know 1 || 0 is 1 means true and application of NOT operator makes it 0 means False:
!( 1 || 0 )
=> ! (1)
=> 0 that is false
Do you notice in this expression we have two operators logical || or and ! NOT operator.
!( 1 || 0 )
^ ^
NOT OR
and notice for OR operator || there is two operands bit single for unary NOT
! operator is used for negation purpose in bool condition checks. There are many places you can use it. Simple example:
if (!existInArray(A, i))
check if i is NOT exist in array.
The point of the ! operator is to make an expression that is false into a true expression. It is most often used as a replacement for == false or == 0. It often makes the expression easier to read:
if (p == NULL || p->next != NULL)
is the same as :
if (!p || p->next)
[Ok, so "easier to read" here is obviously quite subjective].
You have quite a number of answers explaining the NOT operator.
I am not a big fan of the ! operator myself. It is not nearly as visible as it should be (in that, it reverses the meaning of the clause).
For example, despite several years of programming in C++, it still takes me several seconds to parse if ( ! ptr ) as opposed to if ( ptr == NULL ) which instantly conveys me its meaning.
Does if ( ! (i % 2) ) check for even or odd numbers? If you didn't have the answer after your eyes went past the '?', and/or had to review the if condition again, you have just made my case.
Reviewing posts, I agree with some of the posters that the NOT operator has valid uses when applied to bools and function calls. Using ! while processing streams is considered idiomatic.
That said, nearly every programmer I know has been bitten by strcmp. I worked in a shop that has a few #defines such as #define STRCMP_EQUAL 0 etc., and required the check to be written as if ( STRCMP_EQUAL == strcmp(str1, str2) ) which, in my opinion, is orders of magnitude more explicit than if ( ! strcmp(str1, str2) ).
! operator could be used with user defined datatypes(classes and structs in c++).
like every operator(expect . : and ::) !operator could be overloaded. See the following scenario.
//A is empty if memeber size is 0, and no further operations are allowed on other members if
// class is empty.
class A{
int size;
int lot;
int price;
public:
bool operator!()
{
if(lot)
return true;
else
return false;
}
};
A AObj;
//Aobj has size greater than 0
if(!Aobj)
{
//code to Fill or reuse the object.
}
The point of the ! operator is to make an expression that is false into a true expression. It is most often used as a replacement for == false or == 0. It often makes the expression easier to read:
if (p == NULL || p->next != NULL)
is the same as :
if (!p || p->next)
[Ok, so "easier to read" here is obviously quite subjective].

Odd error using intrinsic typecasting in CUDA

I cannot figure out what the difference between the following pieces of code is:
int t = __double2int_rd(pos.x/params.cellSize.x*2.0)&1;
if( t ==0) {...}
and
if(__double2int_rd(pos.x/params.cellSize.x*2.0)&1 == 0) {...}
The second option never returns true, while the first behaves as expected.
Does anyone have any ideas?
The second expression first evaluates (1==0) whose result is always false. Then ANDs it with the result of the function __double2int_rd.
Therefore it actually evaluates:
if(__double2int_rd(pos.x/params.cellSize.x*2.0) & 0)
Which would always be false.
The equivalent of the first expression would be:
if((__double2int_rd(pos.x/params.cellSize.x*2.0) & 1) == 0)
Mind the brackets.
Its a good programming practice to add brackets if you are not sure about the order of evaluation of expressions.