开发者

Pre and postincrement java evaluation

开发者 https://www.devze.com 2023-01-25 06:33 出处:网络
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?

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;


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号