Your question addresses two separate issues.
The first one: Why is I
incremented?
The second one: If the output is 2 1 1
and I
was incremented why aren´t J
and K
incremented then too?
1.
Why is I
incremented?
++
is the increment operator. It increments an operand by 1
count, analogous to the expressions i = i + 1
or i += 1
, where i
stands for the operand.
There is a difference between set ++
in front of (++i
) or behind (i++
) an operand. The answers under the following linked question address the difference at its best, so I won´t go too much in detail about this topic here since the difference is not crucial important at your provided code and I just wanted to annotate that circumstance for that you use the increment operator in your future programs properly and avoid further confusions.
C: What is the difference between ++i and i++?
Back to your code.
Since you use:
printf("%d\n", ++I || ++J && ++K);
I
is immediately incremented by 1
inside the expression, so its value is actually 2
, although this does not influence the logical evaluation because any value which is non-zero would be evaluated as 1
/true
as result of a logical condition test.
That´s why
printf("%d %d %d", I, J ,K);
prints 2
as the value of I
.
2.
Why aren´t J
and K
incremented then too?
Logical testing evaluates from left to right. &&
has a higher precedence than ||
. &&
combined expressions/sub-conditions need to be fulfilled together to be evaluated as true
condition. As soon as a condition becomes true
, which is the case with ++I
, the evaluation of the remaining conditions is omitted since it is redundant.
That´s why J
and K
aren´t incremented by 1
with:
printf("%d\n", ++I || ++J && ++K);
but I
is.
Thus, the correct output of
printf("%d %d %d", I, J ,K);
is:
2 1 1