Efficient detection of signed overflow?

Florian Weimer fw@deneb.enyo.de
Tue Dec 1 20:54:00 GMT 2009


* Mark Dickinson:

> On Tue, Dec 1, 2009 at 12:39 AM, Lawrence Crowl <crowl@google.com> wrote:
>> 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.
>
> This surprises me.  My understanding was that the result of
> a conversion from an unsigned integer type to a signed
> integer type, when the unsigned value doesn't fit into the
> range of the signed type, is merely implementation defined
> rather than undefined behaviour.

There are some who think that, when properly documented,
implementation-defined behavior can result in arbitrary effects, just
as undefined behavior.

> Section 4.5 of gcc's manual seems to say that gcc chooses to wrap
> modulo 2**(width of the signed type) in this case.  Is this likely
> to change in future gcc versions?

I wouldn't rule it out.  Just use -fwrapv (perhaps after benchmarking
to make sure that it doesn't make a difference).  Other compilers will
have similar switches.



More information about the Gcc-help mailing list