public class Prim { public static void main(String[] args) { int i = 1; i = i++ +(( i > 2 )? i++: (i++ * i++)) + i++ ; System.out.println(i); i = 2; i = i++ + (( i > 2 )? i++: (i++ * i++)) + i++ ; System.out.println(i); } } - And what should he do in your opinion? - PinkTux
- The first number is less than the second initially. However, the output is very different - vbn
- and in C ++ it is UB ... in other languages they just think long at the revision code ... - pavel
- Explain why such a strange conclusion is 11 and 9 - vbn
|
1 answer
Two points you need to know:
- Parsing is conducted from left to right
- i ++ - returns the result at the beginning, then increments; ++ i - increment and return result
and everything
i = 2; i = i++ + (( i > 2 )? i++: (i++ * i++)) + i++ ; - at the beginning i ++ is returned - they returned 2 and added 1. In i, the number 3.
- perform actions in brackets: 3> 2? Yes, then we go to the place where i ++
- i was equal to 3, return it and increment it. i is already 4
- it remains to add 4 and i ++. 4 + 4 = 8. Return it and increment it. 8 + 1 = 9
the same with the unit, only this time in the second paragraph there will be 2> 2, instead of 3> 2. And this is clearly a lie. Therefore, let's go not to the point where i ++, but to the point where i ++ * i i ++. Well, then the points described at the beginning.
- Explain, please, why, for example, when
i = 4expressioni + i++will be equal to8? - post_zeew - @post_zeew the second item in the response:
i++ - в начале возвращает результат, потом инкрементирует............ respectively, at the beginning it will add 4 + 4 and return the result as 8 ...... and then only i increment themselves. .... that is,int i = 4; System.out.println(i + i++); System.out.println(i);int i = 4; System.out.println(i + i++); System.out.println(i);will bring out 8 and 5 - Alexey Shimansky - Thank! Here, it seems, is clear. First we display the result on the screen, and only then we increment it . Another question:
int i = 4; i = i + i++; System.out.println(i);int i = 4; i = i + i++; System.out.println(i);. Firsti=4, theni=i+i=4+4=8, and theni++, that is,i=9in the end, but it is8. Why? - post_zeew - @post_zeew because you returned 8 to itself but ...... that is, i already have 8, not 4. And the variable must also be incremented. here it turns out the residual operation must be cranked ............ first, we DO NOT display the result on the screen, but return the result ...... that is,
System.out.println(i + i++)and i I did not assign anything to anything, so he returned the result to 8, and i remained equal to 4, as it was ... Because I did not put it anywhere ....... and then 4 was incremented ..... in the case of yours With examples, everything seems to be kept in mind and is summed up in the same variable%) - Alexey Shimansky - I understand, thank you! - post_zeew
|