error-prone icon indicating copy to clipboard operation
error-prone copied to clipboard

A comparison operator (< > <= >=) between distinct integral types might hide a bug

Open kevinb9n opened this issue 5 months ago • 1 comments

An expression like someInt < someLong is at least "fishy" (no offense to our aquatic friends), because assuming that the wider type actually needs to be wider (can't be safely cast down to the narrower type), then this expression will always have the same result every time it executes. This seems to have some reasonable chance of being not-what-the-user-really-intended.

Example - this loop might never terminate:

long limit = ...
for (int i = 0 ; i < limit ; i++) {
 ...
}

(EDIT: if either operand is a constant expression, this issue doesn't really apply in the same way; we should reason based on its actual value instead of worrying about ranges. Also, this issue doesn't apply in the same when comparing say an int to a double; I was thinking of integral types.)

kevinb9n avatar Nov 10 '25 16:11 kevinb9n

Interesting! I think I would see this example as related to a problem about integer overflow specifically. This code has a similar problem:

int limit = ...;
for (int i = 0; i <= limit; i++) {
  ...
}

if there's any possibility that limit might be Integer.MAX_VALUE.

Are there reasons other than overflow that an inequality comparison between int and long might cause problems?

eamonnmcmanus avatar Nov 10 '25 20:11 eamonnmcmanus