为什么 byte += 1 编译但 byte = byte + 1 不是? [英] why byte += 1 compile but byte = byte + 1 not?

查看:21
本文介绍了为什么 byte += 1 编译但 byte = byte + 1 不是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字节变量:byte b = 0;

If I have a byte variable: byte b = 0;

为什么以下有效:

   b++;
   b += 1; // compiles

...但这不是吗?

   b = b + 1; // compile error

编译器是否首先理解为byte,然后理解为int?

Does compiler understand first as byte and second as int ?

我知道转换,但我想提请您注意 b++、b += 1 和 b = b + 1

I know casting but I want to draw your attention to the b++, b += 1 and b = b + 1

我认为它们是平等的,为什么编译器会区分它们?

I think they are equal so why compiler differs them ? what is the difference between

  b += 1 and b = b + 1 ?

推荐答案

因为 b += 1 等价于 b = (byte)(b + 1), 而 b + 1 的类型被提升为 int (JLS §5.6.2 二进制数字提升),因此如果没有显式转换,其结果不能分配给 byte.

Because b += 1 is an equivalent to b = (byte)(b + 1), whereas type of b + 1 is promoted to int (JLS §5.6.2 Binary Numeric Promotion) and therefore its result cannot be assigned to byte without explicit conversion.

来自 JLS,§15.26.2 复合赋值运算符:

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.

这篇关于为什么 byte += 1 编译但 byte = byte + 1 不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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