简体   繁体   中英

Properly handling the comparison of signed and unsigned values

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) );
}

PS It is a good practice to avoid mixed signed/unsigned comparisons whenever possible since additional compare and a cast can cause a performance loss.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM