Why incrementing int primitive in while loop does not loop forever

自古美人都是妖i 提交于 2019-12-24 03:27:42

问题


I have a following code sample

int i = 1;  

while(i != 0) {  
    i++;  
} 

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?


回答1:


I was expecting this to run in an infinite loop but it didn't.

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

From section 15.18.2 of the JLS:

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.

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.




回答2:


An int is an int: For each i, if i is an int so is i+1. An int is always 32-bits, it never requires a larger container.

Last, your loop is not infinite.



来源:https://stackoverflow.com/questions/21085524/why-incrementing-int-primitive-in-while-loop-does-not-loop-forever

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!