increment operator on single variable -- does post or pre make a difference?

closed account (2EwbqMoL)
Write your question here.
say I have variable N. I dont intend to create any other variables, and I am not comparing it to any other values.

I know that if I were to be using more than one variable, whether I added ++ or -- before or after would make a difference...

but say I am working with a loop or soemthing and I want to increase the value of N by one.

does it matter if I put ++N or N++? will that make a difference?

I dont understand how it could, since N is already the value of N, I think N++ would do the same thing as ++N... unless its evaluating that statement on the value that N was before adding one to itself.

I can see how this might make a difference when comparing two variables (say, M and N, if N= M++ or ++M it would have a different value)...

but if im wrong and it DOES make a difference even with only a single variable, this could cause a mess in my code later on...
The tendency is to prefer pre-increment where either would suffice, since it is generally more efficient for user-defined types (as it doesn't require a copy to be made.)
Last edited on
spiroth10 said:
does it matter if I put ++N or N++? will that make a difference?

I dont understand how it could, since N is already the value of N, I think N++ would do the same thing as ++N... unless its evaluating that statement on the value that N was before adding one to itself.


It does make a difference. I don't think you quite understand exactly what they do.

N++
What this does is create a copy of N and then add one to N. Once the operation is complete, the previous value of N (stored in the copy) is returned. This is why it is considered less efficient than its counterpart, which does not create a copy of the variable.

++N
This simply increments N and then returns N. It doesn't make any copies of the variable, and simply executes the math.

So the difference between the two: post-increment creates an extra copy (un-necessary when used in a typical for-loop) that the pre-increment doesn't.
Last edited on
Topic archived. No new replies allowed.