3

Could you explain step by step how java evaluates

1) the value of y ?

   int x = 5;
   int y = x-- % x++;

2) the value of y in this case?

   int x = 5;
   int y = x-- * 3 / --x;
EugeneP
  • 11,783
  • 32
  • 96
  • 142
  • So many questions about pre/post increment evaluation! – Callum Rogers Nov 17 '10 at 10:31
  • 5
    unless you are compiler writer, you don't need to know. There is no good reason to write code that uses ++ and -- in tricky ways. – Stephen C Nov 17 '10 at 10:38
  • duplicate ? [infinite loop](http://stackoverflow.com/questions/4104944/what-does-x-or-x-do-here) and [X-- X++](http://stackoverflow.com/questions/4104944/what-does-x-or-x-do-here) – NimChimpsky Nov 17 '10 at 10:27

2 Answers2

2

Well, the operands are evaluated from left to right, and in each case the result of a postfix operation is the value of the variable before the increment/decrement whereas the result of a prefix operation is the value of the variable after the increment/decrement... so your cases look like this:

Case 1:

int x = 5;
int tmp1 = x--; // tmp1=5, x=4
int tmp2 = x++; // tmp2=4, x=5
int y = tmp1 % tmp2; // y=1

Case 2:

int x = 5;
int tmp1 = x--; // tmp1=5, x=4
int tmp2 = 3;
int tmp3 = --x; // tmp3=3, x=3
int y = tmp1 * tmp2 / tmp3; // y = 5

Personally I usually try to avoid using pre/post-increment expressions within bigger expressions, and I'd certainly avoid code like this. I find it's almost always clearer to put the side-effecting expressions in separate statements.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Your explanation is correct. However, does `y` have the same value as yours in case 1 and case 2 if you copy&paste EugeneP's question? Having pre- and postdecrement in one line generally isn't considered a good practise, and I haven't got right now a Java compiler to check results :-/ – darioo Nov 17 '10 at 10:38
  • @darioo: Yes, it does give the same answers. I agree it's not a good idea though - will edit to mention that. – Jon Skeet Nov 17 '10 at 10:45
  • Explanation is perfect! And of course, yes, the results are absolutely correct and predictable. – EugeneP Nov 17 '10 at 10:46
0

I'm not sure about java but in C it evolved into undefined behaviour.

Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103