answersLogoWhite

0

++j is the prefix increment operator while j++ is the postfix increment operator. The same applies to --j and j++, the prefix and postfix decrement operators.

The difference between prefix and postfix increment is not the operation itself -- they both increment the operand, which is j. The difference is in the evaluation of that operation -- the value that is returned by the operation.

Prefix will increment j and return a reference to j. Postfix essentially copies j, increments j, and returns a reference to the copy.

In other words:

If j is 1, ++j increments j (so j is 2) and returns a reference to j (which is now 2).

If j is 1, j++ copies j (which is 1), increments j (making it 2) and returns the copy (which is still 1).

When j is a primitive (such as int), no copy is actually made (the return value is pre-emptied by the CPU). Thus there is no difference in terms of performance, the only difference is the return value.

However, when j is a non-primitive, such as a class type, the postfix operator must physically copy the class instance, increment the original instance and then return the copy. As such there will be a performance penalty. If you have no use for the return value, performance will be improved if you use prefix rather than postfix. The more complex the class, the more obvious the difference will become when repeatedly incrementing a class in a loop.

although there is no difference in performance with primitives, it is good practice to use the prefix increment at all times, and use postfix only when you actually need the original value of the operand. Once you get into the habit of using prefix by default, you'll avoid making unnecessary copies of classes other than when you actually need to.

In other words, use for( int x=0; x< 10; ++x ) rather than for( int x=0; x<10; x++ ), regardless of whether x is a primitive or a class type. In both cases, the return value is ignored, but it still exists.

To capture the return value, you must assign it to another variable. Such as int y = x++, or use the operator in a compound expression (where the result is used as part of a larger expression).

Postifx increment is often used with pointers and arrays, to assign a value to the current element being pointed to before advancing the pointer to the next element:

int x[2];

int * p = x;

*p++ = 1; // assigns x[0] and then advances to x[1].

*p = 2; // assigns x[1].

Thus x[0] is 1 while x[1] is 2.

User Avatar

Wiki User

13y ago

What else can I help you with?