Efficient detection of signed overflow?

Mark Dickinson dickinsm@gmail.com
Sun Nov 29 22:00:00 GMT 2009


On Sun, Nov 29, 2009 at 8:53 PM, Florian Weimer <fw@deneb.enyo.de> wrote:
> * Mark Dickinson:
> [...]
>> if ((x^a) < 0 && (x^b) < 0)
>
> Would this test be better?  I think it's equivalent, and it saves a
> comparison.
>
>  if (((x ^ a) & (x ^ b)) < 0)

Mmm.  Quite possibly, yes.  I'll do some timings.

>> Any suggestions for improvements over this?
>
> Use -fwrapv and your first version.

gcc isn't the only compiler that's going to have to compile
this code, so it still needs to be fixed to avoid undefined
behaviour (and I'm worried about -fwrapv inhibiting optimizations
elsewhere in the codebase).  But I guess that casting everything in
sight to unsigned long and then casting the eventual result
back to long, as me22 suggests, would be pretty much equivalent.

On Sun, Nov 29, 2009 at 9:00 PM, me22 <me22.ca@gmail.com> wrote:
> What about using (long)((unsigned long)a + (unsigned long)b) or
> something to get around the UB?

Yep, that looks like the solution.  Thanks!

Mark



More information about the Gcc-help mailing list