My Java teacher said it was better to use ++n instead of n++, I am not seeing the logic behind this. Does anyone know?
Best Answer
++n increments the value and returns the new one.
n++ increments the value and returns the old one.
Thus, n++ requires extra storage, as it has to keep track of the old value so it can return it after doing the increment.
I would expect the actual difference between these two to be negligible these days. I know a lot of compilers will optimize it so they're identical if the return of n++ isn't actually used, though I don't know of Java does that.
Note that the raw grammar lacks any semantics. It's just syntax, and not every syntactically valid program will generally be valid. For example, the requirement that variables have to be declared before usage is typically not covered by the grammar (you can, but it's cumbersome).
Postfix-increment yields an rvalue – and just as you cannot postfix-increment literals, you cannot postfix-increment the result of i++.
Quoting from the JLS (3rd ed., page 486):
The result of the postfix increment expression is not a variable, but a value.
Best Answer
++n
increments the value and returns the new one.n++
increments the value and returns the old one.Thus,
n++
requires extra storage, as it has to keep track of the old value so it can return it after doing the increment.I would expect the actual difference between these two to be negligible these days. I know a lot of compilers will optimize it so they're identical if the return of
n++
isn't actually used, though I don't know of Java does that.