Re: Efficient detection of signed overflow?

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

 



On 11/30/09, Florian Weimer <fw@xxxxxxxxxxxxx> wrote:
> * Mark Dickinson:
> > In practice, yes, I think so.  In theory, no: the result of the
> > conversion is implementation defined for numbers outside the
> > range of the signed type.  (C99 6.3.1.3).  But I'd be surprised
> > if any implementation on a two's complement machine does anything
> > other than just preserve the bit pattern, as you'd expect.
>
> It really depends on your compiler writer's meaning of
> "implementation-defined".  It's not too far-fetched that some
> think that the comparison against zero should be replaced with
> 0 because it can never be true.

Gcc does optimizations based on knowing that signed integer overflow
is undefined behavior.  It may not catch conversion right now,
but given time, it will.  Your best portability bet is to avoid the
overflow by first testing for the conditions under which overflow
will occur.

jmp_buf env;

long add( long a, long b )
{
    long x;
    if ( a > 0 )
        if ( LONG_MAX - a < b )
            longjmp( env, 1 );
        else
            x = a + b;
    else
        if ( LONG_MIN - a > b )
            longjmp( env, 1 );
        else
            x = a + b;
    return x;
}

Yes, it is more expensive than one would like.

-- 
Lawrence Crowl

[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