Correctly handle comparison of signed and unsigned values

I arrived at the point where I need to compare the values ​​with and without a sign. So far, I have always changed the code base to completely avoid this situation, but now I can not do it.

So what is the really correct way to handle a folded and unsigned comparison? This is a mixed C / C ++ code base, so my question applies to both languages.

I check the resource (signed) for the requested value (unsigned).

if (requested > resource.max) return Never; if (requested > resource.free - resource.assigned) return NotNow; return Now; 

I was thinking of something similar (replace C ++ options where applicable):

 if (requested > (unsigned)INT_MAX) bail_out(); // assert,abort,throw,return.... if ((signed)requested > resource.max) return Never; if ((signed)requested > resource.free - resource.assigned) return NotNow; return Now; 

Am I approaching this correctly, or is there a better way?

+8
c ++ c casting unsigned signed
source share
1 answer

You can use this one-line code as a starting point to do this safely:

 bool GreaterSignedUnsigned( unsigned int u, signed int i ) { // calculate the result of (u > i) // if i is nonnegative it is safe to compare 2 unsigned values, // otherwise unsigned int is always greater return ( i < 0 ) || ( u > static_cast<unsigned int>(i) ); } 

PS It’s good practice to avoid mixed comparisons / unsigned comparisons whenever possible, as additional comparisons and casts can lead to performance loss.

+9
source share

All Articles