The following two problems I am having trouble with below are from chapter 5 exercise 3 in "C Programming a Modern Approach" by K.N. King.
1) i = 7; j = 8; k = 9;
printf("%d ",(i = j) || (j = k));
printf("%d %d %d\n", i, j, k);
// answer I think it is 1 9 9 9
// actual answer after running in C: 1 8 8 9
2) i = 1; j = 1; k = 1;
printf("%d ", ++i || ++j && ++k);
printf("%d %d %d\n", i, j, k);
// answer I think it is 1 2 2 2
// actual answer after running in C: 1 2 1 1
My questions are as follows:
Why do the values for i and j in problem 1 not change after assignment in the first printf statement? Since the assignment operator expressions (i = j) and (j = k) are in parenthesis, they get evaluated first from right to left. At this point their values should be 9 and 9. I'm confused why the second printf statement outputs 8 and 8 for i and j?
Why do the values for j and k in problem 2 not change after incrementing in the first printf statement? Since the prefix increments have higher precedence, they are evaluated first for i, j, and k from right to left. At this point their values should be 2, 2, and 2. Like problem 1, why does the second printf statement output 1 and 1 for j and k?
When you have
expr1will be evaluated first.If the result of
expr1is true (aka non-zero),expr2will never be evaluated and the result ofexpr1 || expr2will be 1.If the result of
expr1is false (aka zero)expr2will be evaluated. If the result ofexpr2is non-zero, the result ofexpr1 || expr2will be 1. Otherwise it will be zero.So the line:
can be rewritten as:
Use the same kind of thinking for
printf("%d ", ++i || ++j && ++k);and you'll see why it's onlyithat changes.