Given that x = 2, y = 1, and z = 0, what will the following statement display?
printf("answer = %d\n", (x || !y && z));
It was on a quiz and I got it wrong, I don't remember my professor covering this, someone enlighten me please... I know the answer I get is 1, but why?
The logical AND operator ( && ) returns true if both operands are true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool . Logical AND has left-to-right associativity.
<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .
The circled numbers indicate the order in which C evaluates the operators. The multiplication, remainder and division are evaluated first in left-to-right order (i.e., they associate from left to right) because they have higher precedence than addition and subtraction. The addition and subtraction are evaluated next.
The expression is interpreted as x || (!y &&z)
(check out the precedence of the operators ||
, !
and &&
.
||
is a short-circuiting operator. If the left operand is true (in case of ||
) the right side operand need not be evaluated.
In your case x
is true, so being a boolean expression the result would be 1.
EDIT.
The order of evaluation of &&
and ||
is guaranteed to be from left to right.
If I'm not mistaken, it will print 1. (Let's assume short circuiting is off)
(x || !y && z)
or (true || !true && false)
will first evaluate the ! operator giving (true || false && false)
Then the &&: (true || false)
Then || : true
Printf will interpret true in decimal as 1. So it will print answer = 1\n
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With