简体   繁体   English

正确处理有符号和无符号值的比较

[英]Properly handling the comparison of signed and unsigned values

I arrived at a point where I need to compare singed and unsigned values. 我到达了需要比较singed和unsigned值的点。 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. 这是一个混合的C / C ++代码库,所以我的问题适用于这两种语言。

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): 我正在考虑这样的事情(在适用的情况下替换C ++变体):

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. PS最好尽可能避免混合签名/无符号比较,因为额外的比较和强制转换会导致性能下降。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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