Re: Efficient detection of signed overflow?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



>>> The test was, if I recall correctly
>>>
>>>   x = a + b;
>>>   if ((x ^ a) & (x ^ b)) < 0)
>>>
>>> all you have to do is convert everything to unsigned values, then
>>>
>>>   ux = ua + ub;
>>>   if ((ux ^ ua) & (ux ^ ub)) & (unsigned)INT_MIN))
>>>     goto deal_with_overflow;
>>>   // we now know there is no overflow
>>>   x = ux;
>>>
>>> which is exactly the same test as before, but perfectly compliant.
>>
>> The comment is wrong.  The code checks for signed overflow, but the
>> following assignment still overflwos when ux is larger than INT_MAX.
>> So this version is usable exactly under the same circumstances as the
>> first one.
>
> Ahhh, I see.  Hmm, there must be a decent way to do this.

Oh, it needs to be absolutely portable?  Well, you're already
assuming two's complement.

if (ux <= LONG_MAX) /* or whatever the type was */
  x = ux;
else {
  x = ux + LONG_MIN;
  x += LONG_MIN;
}

should do the trick I think?


Segher


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux