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..

Agash Thamo.
  • 748
  • 6
  • 18
  • @user3145373ツ Yes, it compiles and results in 215 :) – Michał Schielmann Aug 29 '14 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](http://docs.oracle.com/javase/specs/jls/se8/html/). – Edd Aug 29 '14 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. – Stephen C Aug 29 '14 at 10:27
  • @StephenC yeah, true.. but I wanna know it :) – Agash Thamo. Aug 29 '14 at 11:12

4 Answers4

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
assylias
  • 321,522
  • 82
  • 660
  • 783
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
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
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
Manjunath
  • 1,685
  • 9
  • 9
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...

Korashen
  • 2,144
  • 2
  • 18
  • 28