The difference between ++Var and Var++ [duplicate] The difference between ++Var and Var++ [duplicate] java java

The difference between ++Var and Var++ [duplicate]


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.


int a = 5, b;

post increment : b = a++; : a is first transferred to b and then a is incremented, so now b is 5, and a is 6 The effect is b = a; a = a + 1;

pre increment: b = ++a; : first a is incremented and then the result is transferred into b, so now a is 7 and also b is 7. The effect is a = a + 1; b = a

a++ and ++a staying independently act in the similar way. In the loop examples you have presented, the increment operators is not associated in any expression, and are independent. Therefore these two in this particular implementation is identical.


++var is the pre-increment operator; it increments the value of var before evaluating the expression. Similarly, var++ is the post-increment operator; it increments the value of var after evaluating the expression.

In the case of a simple loop, there is no difference between two, because the expressions ++var; and var++; both yield to the same result.

For more info, see for example http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter02/operators.html#IncDecOps.