What is the difference between pre-increment and post-increment in the cycle (for/while)?

user1886376 picture user1886376 · Jun 28, 2013 · Viewed 85.6k times · Source

My interest is in the difference between for and while loops. I know that the post-increment value is used and then incremented and the operation returns a constant pre-increment.

while (true) {
    //...
    i++;
    int j = i;
}

Here, will j contain the old i or the post-incremented i at the end of the loop?

Answer

zennehoy picture zennehoy · Jun 28, 2013

Since the statement i++ ends at the ; in your example, it makes no difference whether you use pre- or post-increment.

The difference arises when you utilize the result:

int j = i++; // i will contain i_old + 1, j will contain the i_old.

Vs:

int j = ++i; // i and j will both contain i_old + 1.