Puzzle 26: In the Loop
有限循环的无限化
有限循环的无限化
这段代码的运行情况会如何?
for (int i = Integer.MAX_VALUE - 5; i <= Integer.MAX_VALUE; i++)
运行后,根本停不了。
回避办法很简单:
int i = Integer.MAX_VALUE - 5;
do {
//...
} while (i++ != Integer.MIN_VALUE);
原因,在Java中:Integer.MAX_VALUE + 1 = Integer.MIN_VALUE,计算如下:
Integer.MAX_VALUE = 0111 1111 1111 1111 1111 1111 1111 1111
+ 1
Integer.MIN_VALUE = 1000 0000 0000 0000 0000 0000 0000 0000
溢出,溢出,Java语言也不去限制一下,这个……
Java Puzzlers云:当你在使用Integer类型时,要小心它的边值问题。(Whenever you use an integral type be aware of the boundary conditions.)
附: