后增量无限循环i + = i ++; [英] Post Increment Infinite loop i += i++;

查看:115
本文介绍了后增量无限循环i + = i ++;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么这个后增量方程不会增加。我原本以为在+ =操作之后,值会增加1,然后第二次我将获得1值。但输出是0零的无限循环。有人能够解释为什么'我'不会增加。

I am not understanding why this post increment equation does not increase. I would have thought that after the += operation the value would increment by 1 and then the second time around i would have a 1 value. But the output is an infinite loop of 0 zero. Is anyone able to explain why 'i' doesn't increase.

int i = 0;
for(; ; ) {
  if ( i >= 10) break;
  i += i++;
}
System.out.println(i);


推荐答案

虽然来自@ njzk2的答案是正确的,但它是有用的指出为什么它是正确的。

While the answer from @njzk2 is correct, it is useful to point out why it is correct.

还有其他可能性 - 例如,为什么Java在赋值后不执行postincrement运算符? (答案:因为这不是Java语言设计师所选择的)

There are other possibilities - for example, why doesn't Java execute the postincrement operator after the assignment? (Answer: because that's not what the Java Language Designers chose)

复合作业的评估顺序(例如 + = )在Java语言规范部分15.26.2中指定。我引用它是怎么回事为Java 8定义

The evaluation order for compound assignments (things like +=) is specified in the Java Language Specification section 15.26.2. I'll quote how it is defined for Java 8:



  • 首先,评估左侧操作数生成变量。如果此评估突然完成,则赋值表达式
    突然完成,原因相同;右边的操作数不是
    评估的,也不会发生任何分配。

  • First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.

否则,保存左边操作数的值,然后保存评估右手操作数。如果此评估突然完成
,那么分配表达式突然完成
同样的原因并且没有分配。

Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

否则,保存的左侧变量值和右侧操作数的值用于执行复合赋值运算符指示的二元运算
。如果此操作
突然完成,则赋值表达式突然以
完成,原因相同并且没有赋值。

Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

否则,二进制运算的结果被转换为左侧变量的类型,受到值集转换
(§5.1.13)到相应的标准值集(不是
扩展指数值集) ),并且转换的结果是
存储到变量中。

Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (§5.1.13) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.

最重要的是首先保存左手表达式的值,然后完全评估右手,然后将复合操作的结果存储在左侧的变量中。

The most important thing is that the value of the left hand expression is saved first, then the right hand is completely evaluated, and then the result of the compound operation is stored in the variable on the left hand side.

这篇关于后增量无限循环i + = i ++;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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