I found something a little strange in C# and Java. Let\'s look at this C++ code:
#include
using namespace std;
class Simple
{
public:
s
According to the Java language specification:
JLS 15.26.2, Compound Assignment Operators
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE
1 is evaluated only once.
This small program demonstrates the difference, and exhibits expected behavior based on this standard.
public class Start
{
int X = 0;
int f()
{
X = X + 10;
return 1;
}
public static void main (String[] args) throws java.lang.Exception
{
Start actualStart = new Start();
Start expectedStart = new Start();
int actual = actualStart.X += actualStart.f();
int expected = (int)(expectedStart.X + expectedStart.f());
int diff = (int)(expectedStart.f() + expectedStart.X);
System.out.println(actual == expected);
System.out.println(actual == diff);
}
}
In order,
actual
is assigned to value of actualStart.X += actualStart.f()
. expected
is assigned to the value of theactualStart.X
, which is 0
, and actualStart.X
withactualStart.f()
, which is 1
0 + 1
to expected
.I also declared diff
to show how changing the order of invocation changes the result.
diff
is assigned to value of thediffStart.f()
, with is 1
, anddiffStart.X
(which is 10, a side effect of diffStart.f()
1 + 10
to diff
. In Java, this is not undefined behavior.
Edit:
To address your point regarding local copies of variables. That is correct, but it has nothing to do with static
. Java saves the result of evaluating each side (left side first), then evaluates result of performing the operator on the saved values.