为什么在while循环中递增int原语不会永远循环 [英] Why incrementing int primitive in while loop does not loop forever
问题描述
我有以下代码示例
int i = 1;
while(i != 0) {
i++;
}
我期望它可以无限循环运行,但事实并非如此.然后,当我在while循环之后打印值时,得到了:
I was expecting this to run in an infinite loop but it didn't. Then when I printed the value after while loop I got:
i value is 0.
任何人都可以让我知道发生了什么吗?
Can any one let me know what exactly is happening?
推荐答案
我期望它可以无限循环地运行,但事实并非如此.
I was expecting this to run in an infinite loop but it didn't.
不,不会. 最终该值将再次变为0.
No, it wouldn't. Eventually the value will become 0 again.
尤其是,它将在逻辑上像这样执行:
In particular, it will logically execute like this:
1
2
3
...
2,147,483,646
2,147,483,647
-2,147,483,648 // Integer overflow => wrapping
-2,147,483,647
...
-3
-2
-1
0
...然后循环将结束
... then the loop will end
来自JLS的第15.18.2节:
如果整数加法溢出,则结果是数学和的低阶位,以某种足够大的二进制补码格式表示.如果发生溢出,则结果的符号与两个操作数值的数学和的符号不同.
If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.
此代码没有内存问题,因为它不执行任何分配-只是在整个堆栈上递增局部变量.
There are no memory issues with this code because it doesn't perform any allocations - it just increments a local variable, entirely on the stack.
现在是否真的是 是另一回事-如果JIT能够在不执行每次迭代的情况下弄清行为将是什么,它就可以对其进行优化-但这是一个实施细节.重要的部分是了解行为背后的逻辑.
Now whether or not it actually does that is a different matter - if the JIT is able to work out what the behaviour will be without executing every iteration, it can optimize it away - but that's an implementation detail. The important part is understanding the logic behind the behaviour.
这篇关于为什么在while循环中递增int原语不会永远循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!