Post Increment in while loop in C
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 + 1while(++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++
is post-increment and ++i
is pre-increment. Post-increment means that the previous value is returned after incrementing the object. Pre-increment means that the object is incremented and then returned. Either way, the object is incremented when its expression is evaluated and that's why you don't get 0
as the first output.
You increment i
after checking it and before printing it. Either increment after checking and printing, or use a do while
loop:
int main(){ int i = 0; do { printf("%d\n", i); } while(i++ < 10); return 0;}