为什么Java增量操作符允许没有显式转换的收缩操作? [英] Why does the Java increment operator allow narrowing operations without explicit cast?
本文介绍了为什么Java增量操作符允许没有显式转换的收缩操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
Java + =运算符
在Java中,这是无效的):
In Java, this is not valid (doesn't compile), as expected:
long lng = 0xffffffffffffL;
int i;
i = 5 + lng; //"error: possible loss of magnitude"
p>
But this is perfectly fine (?!)
long lng = 0xffffffffffffL;
int i = 5;
i += lng; //compiles just fine
这显然是一个缩小操作,可能超过 int
范围。那么为什么编译器不提示呢?
This is obviously a narrowing operation, that can possibly exceed the int
range. So why doesn't the compiler complain?
推荐答案
i + = lng;
i += lng;
compound assignment operator cast's implicitly.
i+=lng;
is same as
i = int(i+lng);
FROM JLS :
形式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.
这篇关于为什么Java增量操作符允许没有显式转换的收缩操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文