简体   繁体   English

Java前缀运算符的行为

[英]Java prefix operator behavior

I was wondering why following code returns 0. I thought num2 will be incremented before applied to *= and the second line would execute num2 = 1*1 我想知道为什么下面的代码返回0。我认为num2将在应用到*=之前递增,第二行将执行num2 = 1*1

int num2 = 0;
num2 *= ++num2;
System.out.println(num2);

From JLS : JLS

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. 形式为E1 op= E2的复合赋值表达式等效于E1 = (T) ((E1) op (E2)) ,其中TE1的类型,只是E1仅被评估一次。

So, your code is equivalent to: 因此,您的代码等效于:

num2 = (int) (num2 * ++num2);

The left-hand operand of the multiplication is zero, thus the result is zero. 乘法的左侧操作数为零,因此结果为零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM