Reputation: 107
I'm reviewing material on C. I'm not sure why the answer is 12 and 32. In the first printf()
, I thought that %d
= 2 (i
), %d
= 2 (j
), \n
= new line. Can anyone explain this?
#include <stdio.h>
int main(void) {
int i,j;
i=2 && (j=2);
printf("%d%d\n",i,j);
(i=3) || (j=3);
printf("%d%d\n",i,j);
}
Upvotes: 0
Views: 136
Reputation: 31376
The reason 12 is printed instead of 22 is because i
is assigned the value of 2 && (j=2)
. First j
gets assigned to 2
. Then (j=2)
returns 2
. After that 2 && 2
is evaluated to true
, and it returns true
. This is because && checks if both sides are true, and 2
is interpreted as true. Since both sides are true, it returns true which is 1.
The ||
does not evaluate right hand side if left is evaluated to true. The reason is that it is not necessary. It should evaluate to true if at least one of the operators evaluates to true, and i=3 evaluates to 3 which is interpreted as true. That's why 32 is printed instead of 33.
The feature that it does not evaluate right operand if left evaluates to true can be used to do this:
foo() || printf("foo() returned false\n");
And similar for &&, but this operator does not evaluate right operand if left evaluates to false.
foo() && printf("foo() returned true\n");
Note that I'm not suggesting that these tricks should be used. I'm just using them as an example of how || and && may skip evaluating the right operand depending on the value on the left.
Upvotes: 0
Reputation: 904
Based on precedences, the first expression is evaluated as
i = (2 && (j=2));
So i=1 (true) and j=2. That is why the first output is 12.
The second expression is a logical OR of two assignments.
(i=3) || (j=3);
But since the first evaluation from left is "true" (i=3) the second evaluation is not done. That is why value of j remains 2 and the second output is 32 (not 33).
Upvotes: 3
Reputation: 402483
For the first expression, i=2 && (j=2);
is implicitly evaluated as i = (2 && (j = 2));
because the assignment operator =
has lower precedence compared to the logical operators. In the first condition, 2 has the truth value of true
, and logical AND &&
causes all conditions to be evaluated, meaning j = 2
is also evaluated, assigning 2 to j
and returning 2 which evaluates to true
. So now the actual expression to be evaluated is i = 2 && 2;
which is true
, or in C's terms, 1. So, i
is assigned 1, and the first output is 12
.
For the second expression (i=3) || (j=3);
, the logical OR ||
is used, and short circuiting ensures that if the first condition evaluates to true
, the overall expression is true
and so the second condition is not evaluated. So after i = 3
is evaluated, i
is assigned 3 and the entire expression is true, so j = 3
is not evaluated. And so the second output is 32
.
Upvotes: 3