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) {}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
tldr;
Although both
var++and++varincrement the variable they are applied to, the result returned byvar++is the value of the variable before incrementing, whereas the result returned by++varis the value of the variable after the increment is applied.Further Explanation
When
++varorvar++form a complete statement (as in your examples) there is no difference between the two. For example the followingis identical to
However, when
++varorvar++are used as part of a larger statement, the two may not be equivalent. For example, the following assertion passeswhereas this one fails
Although both
var++and++varincrement the variable they are applied to, the result returned byvar++is the value of the variable before incrementing, whereas the result returned by++varis the value of the variable after the increment is applied.When used in a
forloop, 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.