tobsob
tobsob

Reputation: 602

Result of function that includes pre- and post-increment differs

I had to understand some code which mixes pre- and post-increments in functions. There was one thing that confused me.

So I tried to test some smaller function. But I could not explain following behaviour:

int i = 1;
i = i++ * ++i * 2;
System.out.println("i = " + i);
int x = 1;
x = ++x * x++ * 2;
System.out.println("x = " + x);

The expected output was:

 i = 8
 x = 8

But actually is:

 i = 6
 x = 8

Can someone tell me why?

Upvotes: 0

Views: 147

Answers (2)

Mena
Mena

Reputation: 48404

  • i++ * ++i * 2 --> 1 * 3 * 2 --> 6
  • ++x * x++ * 2 --> 2 * 2 * 2 --> 8

Important values in bold.

The difference between the prefix and postfix increment when returning values in Java can be better summarized by Oracle themselves (my bold again for highlighting purposes):

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.

Source here.

In your specific case, as the postfix evaluates to the original value and the order of operations is left to right for same arithmetic operator - here, only multiplier applies - your operations are translated as above.

Upvotes: 1

fdfdfd
fdfdfd

Reputation: 501

Post-increment increases the value of i but does not immediately assign the new value of i.

Pre-increment increases the value of i and is immediately assigned the new value.

Thus, in your example for y, after i++,

i has become 2 but it is still holding on to the previous value of 1.

When ++i occurs, i with the value of 2 will be increased by 1 and simultaneously, assigned the new value of 3. Therefore, 1 * 3 * 2 gives us the value 6 for y.

The same goes for x,

when ++x occurs, x is immediately assigned the new value of 2.

However, when x++ occurs, x is increased by 1 but is still assigned the previous value of 2. Therefore, 2 * 2 * 2 gives us 8.

Upvotes: 1

Related Questions