为什么在将 int 与 short 进行比较时,循环条件可以 运行 无限期

why a loop condition can run indefinitely when compares int to short

我的代码中使用了一个循环,coverity 对此抛出了错误 -

Infinite loop, loop_bound_type_mismatch: Loop bound someArray.length has type int, which is wider in size or has a bigger upper bound than the type short of loop counter shortTypeVariable, the loop condition may always be true.

这是引发此错误的示例代码:

short shortTypeVariable = 0;

while(shortTypeVariable < someArray.length) 
{//some work}

我不知道在什么情况下它可以 运行 无限期地。我知道它的匹配条件不正确,但它可能是错误的并且可以 运行 无限期地。

很容易看出解释的意思...

将循环更改为:(33000 假设数组长度较大,宽大于短)

while (shortTypeVariable < 33000)
{
    shortTypeVariable++;
    System.out.println("" + shortTypeVariable);
}

... 然后 运行 看看会发生什么。 short 的数据范围是-32,768 到 32,767。达到 32,767 后,short 溢出到 -32,768 并继续......直到 0,并继续到 32767,在连续循环中再次发生溢出

这是可能的无限循环潜力,因为 int 范围(2,147,483,648 到 2,147,483,647)比 short 范围宽,所以永远无法达到 33000。