I don't understand how to evaluate w1
and w1
.
I know i>1
is 0, j<0
is 0, i<0
is 1, j>0
is 1 and so on, but how do I associate these values?
#include <stdio.h>
int main(void)
{
int i = -1, j = -i;
int w1, w2;
w1 = (i > 0) && (j < 0) || (i < 0) && (j > 0);
w2 = (i <= 0) || (j = 0) && (i >= 0) || (j <= 0);
printf("%d", w1 == w2);
return 0;
}
w1=1
and w2=0
but I know that is incorrect. Can someone explain in detail the process?
CodePudding user response:
Check the operator precedence to have a complete view.
In your case you have this order. First (<,>,<=,>=), then && and finally ||.
So:
w1 = false && false || true && true -> false || true -> true (1)
w2 = true || false && false || false -> true || false || true -> true (1)
and w1==w2 = true (1)
CodePudding user response:
Short-circuiting:
The logical AND and OR operators short-circuit.
From C11:
The AND logical operator:
The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.
4 Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.
6.5.14 Logical OR operator
3 The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.
4 Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.
Assignment vs comparison:
j = 0
assigns 0 to j
. It doesn't test for equality.