This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Efficient detection of signed overflow?


On Mon, Nov 30, 2009 at 1:54 PM, me22 <me22.ca@gmail.com> wrote:
> 2009/11/30 Florian Weimer <fw@deneb.enyo.de>:
>>
>>> 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?
>>
>> You'd also have to compare against (1 << (sizeof(long) * CHAR_BITS -
>> 1)) instead of 0, pessimizing the code somewhat.
>>
>
> Why? ÂIf numbers are 2s-complement, the cast back to a signed type is
> well-defined, isn't it?

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.

Mark


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]