Properly handling the comparison of signed and unsigned values

Viewed 864

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?

1 Answers
Related