Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
Šimon Tóth Avatar asked Jul 31 '12 08:07

Šimon Tóth


1 Answers

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.

like image 188
Sergey K. Avatar answered Oct 13 '22 01:10

Sergey K.