I am trying to have id1 be one step ahead of count(number-wise). I was trying to accomplish this with the prefix version of the increment operator, but this produced odd behavior.
What I planned on happening was 1. count would be initialized to zero. 2. id1 would be initialized to ++count( which due to the the prefix increment operator would be incremented before id1 was set to its value making id1 equal one while count still equaled zero.) 3. I would print count.
When I printed count, however, I found out that the code id1(++count) was incrementing count as well as setting id1 to ++count.
Why does this happen? It seems inconvenient for setting values for ints to also increment other variables in the process. How do I avoid this? Can I write it in such a way that it still displays that my intent for it to be one higher than count or is that just not possible?
There is a difference between pre-inc and post-inc (same for pre-dec and post-dec).
pre-inc (++i) first increments i and then returns the new value of i as the result of the expression. So z = ++i first increments i and this incremented value is then assigned to z
post-inc (i++) returns the current value of i for the result of the expression and then increments i. So z = i++ assigns the current value of i to z and then increments i.
If the result of the expression is not used, then logically there is no difference between pre-inc and post inc. These only have different outcomes if the result is used.
If you have a choice (ie the result isn't used), then choose pre-inc. For a POD type, this has no difference but for some classes, using a post-inc incurs an extra copy which could impact performance.