0

I know there are several question about the x++ operation, I know the difference between ++x and x++. But now I have to solve this:

int x = 5; x += x++ * x++ * x++; 

Well I know that this shouldn't be too difficult, but still, I need an explanation how this calculatino is done, step by step, I don't get it by myself..

4
  • @user3145373ツ Yes, it compiles and results in 215 :) Commented Aug 29, 2014 at 10:20
  • Have you run the code? I'd look at running a few permutations of this until you can figure out what's going on (0 += x++ * x++ * x++, x += x++ * x++, x += (x++ * x++) * x++, etc.), or consult the JLS. Commented Aug 29, 2014 at 10:20
  • You should never ever write code like this, and never ever need to read it. So you could argue that knowing the solution is ... pointless. Commented Aug 29, 2014 at 10:27
  • @StephenC yeah, true.. but I wanna know it :) Commented Aug 29, 2014 at 11:12

4 Answers 4

8

Your code is equivalent to:

int x = 5; int originalX = x; int a = x++; int b = x++; int c = x++; x = originalX + a * b * c; System.out.println("x = " + x); //215 
Sign up to request clarification or add additional context in comments.

4 Comments

+1. This is the best answer here.. :)
@TheLostMind I agree
Wow, short and simple answer. I didn't try to cut it in small pieces, don't know why I didn't came up with that.
2
x += x++ * x++ * x++; 

can be written as:

x = x+ x++ * x++ * x++; 

how will it be evaluated? x= 5+(5 * 6 * 7) because you are using postfix. So, the incremented value of x will be visible from the second time it is used.

So, final output = 5+ (5*6*7) == 215 

Comments

1

x++ would mean read the value and use it in the place which is referenced and then increment it.

So in your question:-

int x = 5; x = 5 + 5 * 6 * 7 x += x++ * x++ * x++; x = 215 

Comments

1
int x = 5; x += x++ * x++ * x++; 

First, set some brackets to better see the calculation sequence:

x += ((x++ * x++) * x++); 

Then, replace the first occurance of x with it's value, calculate, and continiue replacing with updated values:

5 += ((x++ * x++) * x++); 5 += ((5 * x++) * x++); 5 += ((5 * 6) * x++); 5 += ((5 * 6) * 7); 5 += 210; 

and now, it's plain math...

Result should be: 215

And my compile gives me: 215

So I think my explanation is correct. But i'm not 100% sure...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.