문제

Please check the following peices:

byte a=1, b=2;  b+=a;

is perfectly legal. While,

byte a=1, b=2;  b=b+a;

is not allowed. Although both of these are considered equivalent. Is there any difference in the mechanism of the two ways of assignment?

도움이 되었습니까?

해결책

From the language specification:

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.

This means that b+=a is equivalent to (byte)(a+b), instead of simply a+b. The latter still needs a cast to byte.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top