Why does (0 && 1 == 0) not evaluate to true? - c++

In my if statement, the first condition for && is 0 (false), so the expression 0 && (a++) is equal to 0, right? Then 0==0 it should be true. Why am I getting else here? Please explain!
int a=0;
if(0 && (a++)==0)
{
printf("Inside if");
}
else
{
printf("Else");
}
printf("%i",a);

The == operator has a higher priority than the && operator, so this line:
if(0 && (a++)==0)
is treated like this:
if( 0 && ((a++)==0) )
So the whole expression under the if is false, and a++ is not even evaluated due to short circuitry of the && operator.
You can read about Operator Precedence and Associativity on cppreference.com.
When in doubt, you should use parenthesis to express your intention clearly. In this case, it should be:
if( (0 && (a++)) == 0 )
Though, it does not make any sense, as it always evaluates to true and a++ is not incremented here, either.

As already mentioned, the precedence of == is higher than precedence of &&, so the statement is resolved into
if( 0 && ((a++)==0))
However, still even if you add the correct order of brackets, a++ returns the original value of a, which is 0, but the a is incremented. If you want to return the updated value of a, you should write ++a
if( ((++a) && 0) == 0 )

Although the question seems easy it's very error-prone.
We need to know the precedence of various operators involved in this.
1. postfix (++)
2. ==
3. Logical AND (&&)
the final expression can be seen as: if ( (0 && (a++)) == 0 )
which is true. Hence statement under if is evaluated to be true.

Related

How Precedence of Relational Operator handled in C++

According to precedence rules <, >, <=, >= has precedence over !=, ==
I am so confused that how the following statement will be executed
int a=3, b=3;
cout<< (a != b || a <= b);
I know short circuit evaluation and according to precedence rules I guess that compiler will execute a <= b first as it has precedence over != but it is not doing so.
I did little experiment with above statement by changing a <= b-- and changing order of above conditions and it seems that <= and != have same precedence as compiler execute whichever occurred first. Or I am missing something?
Precedence of operators is only relevant to how expressions are bound, not to how they're executed. Execution order is dependent on the "happens-before" relationship and otherwise subject to arbitrary reordering by the compiler.
Relative precedence of two operators also only matters if they are directly adjacent. In a == b <= c, you get a == (b <= c), not (a == b) <= c. In a == b || c <= d, the adjacent pairs are == and || and || and <=. In both cases the comparison operators bind more strongly, so you get (a == b) || (c <= d), making the relative precedence of == and <= irrelevant. If you have a == b + c <= d instead, you first get a == (b + c) <= d, and now you need to compare == and <= again, getting you a == ((b + c) <= d).
As for order of evaluation, || has a rule that its left side is sequenced before its right side (assuming it's not overloaded), because the right side might not get evaluated at all. So the == is executed first. But precedence plays no part at all in this. If you instead had written the non-short-circuiting a != b | a <= b, both sides would eventually get executed (with caveats, see below), but there are no guarantees which side gets evaluated first; precedence does not play a part here.
Caveat: the compiler can still just optimize your code and realize that a != b || a <= b is tautological, and simply replace the entire thing with true.
Precedence is not order of evaluation.
Precedence is about where to put parentheses. a != b || a <= b is parsed as: (a != b) || (a <= b). It's not parsed as like for example: a != (b || (a <= b)) or any other combination of ( ).
After we know where parentheses are, then we can evaluate the expression. The order of evaluation is: (a != b) first. Then || is evaluated. Then, optionally, a <= b is evaluated.
From: https://en.cppreference.com/w/cpp/language/operator_logical
You are looking for the part in ( )
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
So a != b will be evaluated first.
In your case 3 != 3 so the second operand will be evaluated.
if( (5<5) || (5!=5) || (5==5) || (5>5) )
The precedence left to right, so 5<5, goes to next 5!=5 goes to next 5==5 operand if returns true and 5>5 is not evaluated.
As per Microsoft doc,
The operator <= >= < > has higher precedence than the operator != ==. But as you have applied the logical or || operator the expression will be executed from left to right.
It will handle it as ( ( a != b ) || ( a <= b ) ) meaning, first ( a != b ) will be check, after that, logical ||, and if there's need than this expression ( a <= b ) will be checked ( only if the first expression ( a != b ) is wrong).

Find a logical expression that is true if `n` is a multiple of `2019` and is not in the interval `(a, b)`

I had the task of finding a logical expression that would result in 1 if and only if a given number n is a multiple of 2019 and is NOT from the interval (a, b).
The textbook gave the following answer and I don't really understand it:
a>=n || b<=n && (n%3==0 && n%673==0)
The thing between those parantheses I understand to be equivalent to n%2019==0, so that's alright. But I don't understand why this works, I mean the && operator has higher priority that the || operator, so wouldn't we evaluate
b<=n && (n%3==0 && n%673==0)
first and only at the end if n<=a? I thought that if I were to do it, I would do it like this:
(a>=n || b<=n) && (n%3==0 && n%673==0)
So I just added that extra set of parantheses. Now we would check if the number is not in the interval (a, b), then we would check if it is a multiple of 2019 and then we would 'and' those to answers to get the final answer. This makes sense to me. But I don't understand why they omitted that set of parantheses, why would that still work? Shouldn't we consider that && has higher priority than ||, so we add an extra set of parantheses? Would it still work? Or is it me that is wrong?
Trying it out shows that the expression as written without the extra parentheses doesn't work:
bool expr(int n, int a, int b)
{
return a>=n || b<=n && (n%3==0 && n%673==0);
}
expr(1000, 2000, 2018) for example evaluates to true, even though it is not a multiple of 2019.
As you pointed out, the logical AND operator && has higher precedence than the logical OR operator || (reference), so the expression is equivalent to:
a>=n || (b<=n && (n%3==0 && n%673==0))
which is always true when n <= a, even if it's not a multiple of 2019.
A clearer expression would be:
(n % 2019 == 0) && (n <= a || n >= b)

AND and OR operator [duplicate]

This question already has an answer here:
Short circuit behavior of logical expressions in C in this example
(1 answer)
Closed 7 years ago.
Aren't the individual expressions in a composite logical AND/OR expression supposed to be evaluated first before the logical operators are applied to their result?Why is ++k untouched in the condition m = ++i && ++j || ++k for the following program :
#include<stdio.h>
int main()
{
int i=-3, j=2, k=0, m;
m = ++i && ++j || ++k;
printf("%d, %d, %d, %d\n", i, j, k, m);
return 0;
}
Output : -2,3,0,1
But I expect the output -2,3,1,1
You should avoid coding such unreadable code. It is actually parsed as
m = (++i && ++j) || ++k;
So once j >= 0 the ++j condition is always true, so ++k is not evaluated since && is a short-cutting and then but || is a short-cutting or else (so they may not evaluate their right operand).
So && is evaluated as follow: the left operand is evaluated, if it is false it is returned, and then only when it is true (i.e. not equal to 0) the right operand is evaluated and returned as the evaluated result of the &&. Likewise || is evaluated as follow: the left operand is evaluated. If it is true (non-zero) it becomes the result of the ||; or else the right operand is evaluated and is the result of the || expression.
In particular, when coding if (x > 0 && 20/x < 5) the division is never attempted for x==0 .
Read also the wikipedia operators in C & C++ & short circuit evaluation & lazy evaluation pages; and please take several hours to read a good C programming book.
Logical operators have short circuit evaluation, i.e. as soon as a value is determined for the expression, the rest of the expression is not evaluated.
e.g. m = ++i && ++j || ++k;
in this ++i -> true, ++j -> true (non zero value)
hence m = true && true || ++k;
now true && true is true
so
m = true || ++k
As in OR operator if 1 side is true, the other is not evaluated so result is true.
Hence k is not incremented.
That is a shortcut for logical operators, in your case operator ||. When the first operand is true, it's impossible for the second operand to have any impact on the result. It will always be true, not matter what the second operand may yield. So the second operand is not evaluated.
The same goes for the logical && operator, if the first operand is found to be false. The second operand will not matter, the result will always be false and the second operand will therefor not be evaluated.
&& and || are logical operators, and you are using them out of context which is odd (ok for C/C++ but you'd have type errors in Java or C#).
You've have just discovered short circuiting operators - you don't need to evaluate the whole expression if you "know" it's true. i.e. i and j are non zero so you don't need to do anything with k since you know the expression is true.
m = ++i && ++j || ++k;
Above line of code executes ++i and ++j first and doesn't execute ++k since it's written after || (OR)
Logical Circuit Operators don't execute when previously statement is true already in case of || and false in case of &&
Hence k is untouched

c++ what is the correct syntax here?

what is the correct syntax for checking a varable value and then setting a varable in the same condition also checking that new set varables var, all in one if statement?
so basically something like
if(this->somevar > 0 && this->newvar = this->GetNewVar(this->somevar),this->newvar > 0)
i know that is not the correct syntax or at least its not working for me anyway, hence the topic, i am using that as an example, so if this->somevar is null or 0, i don't want it to execute the next condition which is && this->newvar = this->GetNewVar(this->somevar,this->newvar but instead skip the statement and ignore that part.
what is the correct syntax for something like this?
&& is an operator with short circuit evaluation, right part is not executed if left part is true.
But why don't you simply write:
if(this->somevar > 0)
{
this->newvar = this->GetNewVar(this->somevar);
if (this->newvar > 0)
{
...
This will certainly makes things clearer ...
the logical AND && operator is short-circuited if this->somevar evaluates to zero, meaning the rest of your if expression would not be evaluated in that situation
The expression after the comma is not necessary. Also, there is one thing missing, parentheses arround the assignment:
if(this->somevar > 0 && (this->newvar = this->GetNewVar(this->somevar)) > 0)
Without the parentheses you may end up setting this->newvar to the value of the boolean expression
this->GetNewVar(this->somevar),this->newvar > 0, which will be evaluated to a boolean result (true/false which, in turn, may be converted to 0 or 1 or -1 depending on the compiler, when cast to the type of this->newvar).
I think only the bit after the comma is evaluated for the if condition. The expression on the left of the comma is ignored.
int main() {
if( false, true) { cout << " got to if( false, true ) "; }
if ( true, false ) { cout << "got to if( true, false ) "; }
}
to answer your question, you can put anything on the left of the comma and do whatever you like, as long as the expression you want to evaluate is the last expression in the list.
so if ( exp1, exp2, exp3 , exp4 ) dowhatever(); only gets run if exp4 is true. You should really run exp1 to exp3 outside the if condition for readability.

Confused about if condition CPP

Confused about if condition, how does it executes following statements.
if(1 && (1 || 0) != 0) or if(1 || (1 && 0) != 0)
In above if statement what is the sequence of executing/validating the statements.
(left to right or right to left) if left to right, then if first argument/expression is true does it evaluates 2nd expression/argument? is it true for both the logical AND and OR operators.
Thanks.
Logical && short circuits if the first operand evaluates to false (because false && x is false for all x)
Logical || short circuits if the first operand evaluates to true (because true || x is true for all x)
They both evaluate left-to-right.
It's left to right
First executes 1. Then executes (1 || 0) != 0. To do that it executes 1 || 0 -> true, so the whole thing is true.
First executes 1 - it's true, so it short circuits and returns true.
It's left to right. || short-circuits if first expression is true, && if first expression is false.
Both things are fundamentally different go read D Morgans Laws!s
lets break it down step-by-step:
(1 || 0) becomes true as 1 short-circuits the expression
so (1 || 0) != 0 is true
1 && true is true by the definition of the logical && operator
or is a define/keyword for || but the first section is already true, so we short-circuit the expression again and the code inside the if block is executed.