Post Increment in while loop in C

algo picture algo · Aug 28, 2014 · Viewed 30.9k times · Source

Here is a very simple C program:

int main()
{
    int i = 0;
    while(i++ < 10)
         printf("%d\n", i);

    return 0;
}

The result is:

1
2
3
4
5
6
7
8
9
10

Why 0 is not the first number to print? And if I replace the i++ with ++i I'll get this:

1
2
3
4
5
6
7
8
9

For both i++ and ++i the first number is 1.
I expected to see the 0 for post increment in while loop while().
Thanks.

Answer

paxdiablo picture paxdiablo · Aug 28, 2014

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.