s = s + s和s + = s之间的差异为短 [英] Difference between s = s + s and s += s with short

查看:290
本文介绍了s = s + s和s + = s之间的差异为短的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一点测试来操作,我遇到了编译问题。
以下代码编译:

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;

虽然这个没有:

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

我读过短裤会自动提升为 int ,但这两个代码有什么区别?

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

推荐答案

你是对的被提升为 ints 。这在评估二元运算符 + 期间发生,它被称为二进制数字促销

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.

但是,使用复合赋值运算符(例如 + = )可以有效地删除它。 JLS的
15.26.2节
状态:

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


E1 op = E2形式的复合赋值表达式等效于E1 =(T)((E1) op(E2)),其中T是E1的类型,除了E1仅被评估一次。

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.

这篇关于s = s + s和s + = s之间的差异为短的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆