The i++
(and ++i
) is done as part of the while
expression evaluation, which happens before the printing. So that means it will always print 1
initially.
The only difference between the i++
and ++i
variants is when the increment happens inside the expression itself, and this affects the final value printed. The equivalent pseudo-code for each is:
while(i++ < 10) while i < 10:
i = i + 1
printf("%d\n", i); print i
i = i + 1
and:
i = i + 1
while(++i < 10) while i < 10:
printf("%d\n", i); print i
i = i + 1
Let's say i
gets up to 9
. With i++ < 10
, it uses 9 < 10
for the while
expression then increments i
to 10 before printing. So the check uses 9 then prints 10.
With ++i < 10
, it first increments i
then uses 10 < 10
for the while
expression. So the check uses 10 and doesn't print anything, because the loop has exited because of that check.
i
after it was modified, so how can you see0
!? – Evolutionarywhile(i++ < 10) /*i is incremented here*/ printf("%d\n", i);
– Weighted