Search code examples
javaintprimitive-typesshort

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


There is a loop used in my code, for which coverity is throwing the error -

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.

This is a sample code for which this error is thrown :

short shortTypeVariable = 0;

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

I am not able to figure in which condition it can run indefinitely. I know its not right condition to match but when it can be wrong and can run indefinitely.


Solution

  • It is easy to show what the explanation means...

    Change the loop to have: (33000 assumes a large array length, wider than short)

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

    ... then run it to see what happens. The data range of short is -32,768 to 32,767. After 32,767 is reached, the short overflows to -32,768 and keeps going... up to 0, and continues up to 32767 where the overflow happens again in a continuous cycle.

    That is the possible infinite loop potential, as 33000 can never be reached because the int range (2,147,483,648 to 2,147,483,647) is wider than the short range.