Question

Please check the following peices:

byte a=1, b=2;  b+=a;

is perfectly legal. While,

byte a=1, b=2;  b=b+a;

is not allowed. Although both of these are considered equivalent. Is there any difference in the mechanism of the two ways of assignment?

Was it helpful?

Solution

From the language specification:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

This means that b+=a is equivalent to (byte)(a+b), instead of simply a+b. The latter still needs a cast to byte.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top