Pre and postincrement java evaluation

2019-07-04 08:03发布

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;

标签: java
2条回答
ら.Afraid
2楼-- · 2019-07-04 08:16

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

查看更多
一夜七次
3楼-- · 2019-07-04 08:32

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.

查看更多
登录 后发表回答