java - 为什么 i+=l 会编译,其中 i 是 int 而 l 是 long?

标签 java variable-assignment compound-operator

我发现了 Java's +=, -=, *=, /= compound assignment operators (好问题 :)),但它有一部分我不太明白。借用那个问题:

int i = 5;
long l = 8;

Then i = i + l; will not compile but i += 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 值添加到 bytechar 变量时会出现类似的“意外”——赋值运算符有效,而普通加法运算符无效。

关于java - 为什么 i+=l 会编译,其中 i 是 int 而 l 是 long?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8713397/

相关文章:

java - Checkmarx 资源访问授权不当

c - 在c中的字符串末尾获取^D

c - 这是错误的还是我遗漏了什么(int count = 10, x;)

C - 逻辑复合运算符

java按位运算符和相等字符;复合运算符

java - 无法将 "IN"与 JPA 查询一起使用

java - 在 AudioInputStream 上设置超时

java - 重写 JButton 中的 Paint() 方法

Java风格: Multiple variable assignment

java - 自动捕获 Java 中 =+ 而不是 += 的使用