0

Need help with java sintax.

please help with code: int r =7; r +=r+=-2; can somebody explaine why r = 12?

20th Aug 2018, 11:12 AM
sergey
6 Answers
+ 2
The first statement is: r = 7; The second statement is: r += r += -2; In the second statement, java will first decrement the variable r by 2. Which equivalent to: r += (7 - 2); Then it will increment r by 5. r = 7 + 5; it's equivalent to the following: r = 7; r = (r + (r - 2)); In general: a = b = c = 10; java first will set c to 10, then it will set b to the value of c, then it will set a to the value of b.
20th Aug 2018, 11:47 AM
Mohammed
+ 8
Ipang I also thought that...but why does it show 10 in C++? :/
20th Aug 2018, 11:40 AM
Nikhil
Nikhil - avatar
+ 7
Ipang Ohh... Thank you ^_^
20th Aug 2018, 1:28 PM
Nikhil
Nikhil - avatar
+ 4
Nikhil so with a help from a friend I found out, that it turned out the nesting of += operator in the expression to C++ is considered as a possible undefined order operation, so in this case, the right most operation (r += -2) is calculated first, then, r which is now 5, summed up to 10, that's how C++ puts the operation order. Of course, with C/C++ this is not considered a good practice, just as it is with mixing up postfix & prefix operators together, in a single line : )
20th Aug 2018, 12:43 PM
Ipang
+ 3
The += operator evaluates operands to its right, so it is equal to: r += (r += -2) r = r + (r -2) r = 7 + 5 => 12
20th Aug 2018, 11:38 AM
Ipang
+ 2
Nikhil That's right, unfortunately, I can't explain the odds either, I guess it's just how C++ does things differently to Java : )
20th Aug 2018, 12:01 PM
Ipang