0

I get stuck in the last expression,

shouldn't the calculation step for int z = x-- + 2*x be: int z = (9) + 2(9)= 27?

However, when I try to run it, the assignment to int z turns out to be 25, why?

Below is the expressions:

int x = 10;

int y = --x + x;

int z = x-- + 2*x;

And the result is:

[1] x = 10

[2] x = 9; y = 18

[3] x = 8; z = 25
Jonah Williams
  • 20,499
  • 6
  • 65
  • 53
Yoyashi
  • 23
  • 7
  • 1
    `x--` is **post**-decrement operator. So, the value of the `x` will be used in expression first and then decrement. – Tushar Nov 08 '15 at 10:11
  • 1
    http://stackoverflow.com/questions/1546981/post-increment-vs-pre-increment-javascript-optimization duplicate? – EugenSunic Nov 08 '15 at 10:12

1 Answers1

1

At start

int x = 10;

when you run

int y = --x + x;

x got decremented by -1 then x become 9 so 9+9 = 18

in this line

int z = x-- + 2*x;

First x was 9 then got decremented by -1 then x become 8 so 9+8*2 = 25

N:B

  • pre increment/decrements execute first like ++x/--x;
  • post increment/decrements execute last like x++/x--
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80