The difference between post- and pre-increment is really, in many cases subtle. post incremenet, aka num++
, first creates a copy of num
, returns it, and after that, increments it. Pre-increment, on the other hand, aka ++num
, first evaluates, then returns the value. Most modern compilers, when seeing this in a loop, will generally optimize, mostly when post increment is used, and the returned initial value is not used. The most major difference between the 2 increments, where it is really common to make subtle bugs, is when declaring variables, with incremented values: Example below:
int num = 5;
int num2 = ++num; //Here, first num is incremented,
//then made 6, and that value is stored in num2;
Another example:
int num = 5;
int num2 = num++; //Here, num is first returned, (unfortunately?), and then
//incremented. This is useful for some cases.
The last thing here I want to say is BE CAREFUL WITH INCREMENTS. When declaring variables, make sure you use the right increment, or just write the whole thing out (num2 = num + 1
, which doesn't always work, and is the equivalent of pre-increment). A lot of trouble will be saved, if you use the right increment.
i
is a primitive type, there is no difference between these two. – Massy