9

I made a little test to manipulate a short and I came across a compilation problem. The following code compile :

short s = 1;
s += s;

while this one doesn't :

short s = 1;
s = s + s; //Cannot convert from int to short

I've read that shorts are automatically promoted to int, but what's the difference between those two codes ?

rgettman
  • 176,041
  • 30
  • 275
  • 357
Patrick
  • 831
  • 11
  • 25

1 Answers1

17

You're right that short are promoted to ints. This occurs during the evaluation of the binary operator +, and it's known as binary numeric promotion.

However, this is effectively erased with compound assignment operators such as +=. Section 15.26.2 of the JLS states:

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.

That is, it's equivalent to casting back to short.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • I liked your answer more than mine, than you got up-vote and i removed mine, Good Job. – Orel Eraki Jan 23 '14 at 17:15
  • 1
    @Patrick: There is another way in which compound assignment differs. Clearly `x *= y + z;` does not mean `x = x * y + z;` but rather `x = x * (y + z);`. Well, the same is true of `+`. `x += y + z` means `x = x + (y + z)`, not `x = x + y + z`. The right-hand addition happens *before* the left-hand addition when you use `+=` in this manner. In algebra addition is associative and commutative, but computer math can violate these properties. The result of `x += y + z` need not be the same as `x = x + y + z`. – Eric Lippert Jan 23 '14 at 23:54