Option to make unsigned->signed conversion always well-defined?

Ulf Magnusson ulfalizer@gmail.com
Fri Oct 7 17:13:00 GMT 2011


On Fri, Oct 7, 2011 at 10:37 AM, Andrew Haley <aph@redhat.com> wrote:
> On 10/06/2011 07:24 PM, Ulf Magnusson wrote:
>> bool overflow_unsafe(unsigned int a, unsigned int b) {
>>     const unsigned int sum = (int8_t)a + (int8_t)b;
>>     return (int8_t)sum != sum;
>> }
>>
>> bool overflow_safe(unsigned int a, unsigned int b) {
>>     const int sum = as_signed_8(a) + as_signed_8(b);
>>     return as_signed_8(sum) != sum;
>> }
>
> I get this:
>
> overflow:
>        sxtb    r1, r1
>        sxtab   r1, r1, r0
>        sxtb    r0, r1
>        subs    r0, r0, r1
>        it      ne
>        movne   r0, #1
>        bx      lr
>
> It's not obvious to me how you'd improve on it.
>
> Andrew.
>

Nah, might be the best all-around version. Seems to generate the
nicest code when you make use of the sum afterwards as well.

/Ulf



More information about the Gcc-help mailing list