Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between s = s + s and s += s with short [duplicate]

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 ?

like image 974
Patrick Avatar asked Jan 23 '14 17:01

Patrick


1 Answers

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.

like image 179
rgettman Avatar answered Oct 24 '22 20:10

rgettman