Reputation: 537
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.
Upvotes: 1
Views: 158
Reputation: 26171
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.
Upvotes: 0
Reputation: 25739
It's left to right. || short-circuits if first expression is true, && if first expression is false.
Upvotes: 0
Reputation: 93030
It's left to right
(1 || 0) != 0
. To do that it executes 1 || 0 -> true, so the whole thing is true.Upvotes: 1
Reputation: 54270
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.
Upvotes: 4