0
Need help with java sintax.
please help with code: int r =7; r +=r+=-2; can somebody explaine why r = 12?
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.
+ 8
Ipang I also thought that...but why does it show 10 in C++? :/
+ 7
Ipang Ohh... Thank you ^_^
+ 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 : )
+ 3
The += operator evaluates operands to its right, so it is equal to:
r += (r += -2)
r = r + (r -2)
r = 7 + 5 => 12
+ 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 : )