I arrived at a point where I need to compare singed and unsigned values. Until now I always modified the code base to avoid this situation completely, but now I can't do that.
So what is the really proper way to handle singed and unsigned comparison? This is a mixed C/C++ code base, so my question applies to both languages.
I'm checking a resource (signed) against requested value (unsigned).
if (requested > resource.max) return Never;
if (requested > resource.free - resource.assigned) return NotNow;
return Now;
I was thinking about something like this (substitute C++ variants 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 some better way?
You can use this one-liner code as a starting point to do it 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) );
}
P.S. It is a good practice to avoid mixed signed/unsigned comparisons whenever possible since additional compare and a cast can cause a performance loss.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With