我发现了 Java's +=, -=, *=, /= compound assignment operators (好问题 :)),但它有一部分我不太明白。借用那个问题:
int i = 5; long l = 8;
Then
i = i + l;
will not compile buti += l;
will compile fine.
链接问题的已接受答案指出:
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.
给出 i += l;
与 i = (int)((i) + (l));
相同,除了 >i
只计算一次。
long
可能(IIRC 甚至保证)比 int
长,因此可以容纳更大范围的值。
鉴于这种情况很容易在执行语句(右值表达式求值或赋值)的某个时刻由于必要的收缩转换而导致数据丢失,为什么 i += l;
不是编译时错误或至少是警告?
最佳答案
基本上,因为 i += l
的编译就像是写成 i = (int) (i + l)
一样。将 int
值添加到 byte
和 char
变量时会出现类似的“意外”——赋值运算符有效,而普通加法运算符无效。
关于java - 为什么 i+=l 会编译,其中 i 是 int 而 l 是 long?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8713397/