Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre and postincrement java evaluation

Tags:

java

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;
like image 290
EugeneP Avatar asked Sep 07 '26 17:09

EugeneP


1 Answers

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.

like image 114
Jon Skeet Avatar answered Sep 10 '26 08:09

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!