The difference between ++Var and Var++

user559142 picture user559142 · May 30, 2011 · Viewed 89.2k times · Source

In programming, particularly in Java, what is the difference between:

int var = 0;
var++;

and

int var = 0;
++var;

What repercussions would this have on a for loop?

e.g.

for (int i = 0; i < 10; i++) {}

for (int i = 0; i < 10; ++i) {}

Answer

D&#243;nal picture Dónal · May 30, 2011

tldr;

Although both var++ and ++var increment the variable they are applied to, the result returned by var++ is the value of the variable before incrementing, whereas the result returned by ++var is the value of the variable after the increment is applied.

Further Explanation

When ++var or var++ form a complete statement (as in your examples) there is no difference between the two. For example the following

int x = 6;
++x;
assert x == 7;

is identical to

int x = 6;
x++;
assert x == 7;

However, when ++var or var++ are used as part of a larger statement, the two may not be equivalent. For example, the following assertion passes

int x = 6;
assert ++x == 7;

whereas this one fails

int x = 6;
assert x++ == 7;

Although both var++ and ++var increment the variable they are applied to, the result returned by var++ is the value of the variable before incrementing, whereas the result returned by ++var is the value of the variable after the increment is applied.

When used in a for loop, there is no difference between the two because the incrementation of the variable does not form part of a larger statement. It may not appear this way, because there is other code on the same line of the source file. But if you look closely, you'll see there is a ; immediately before the increment and nothing afterwards, so the increment operator does not form part of a larger statement.