Difference between s = s + s and s += s with short

落爺英雄遲暮 提交于 2019-12-22 04:06:54

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/21314877/difference-between-s-s-s-and-s-s-with-short

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!