On 01/27/2011 10:57 AM, Paul Eggert wrote:
>>>> # define TYPE_MAXIMUM(t) \
>>>>   ((t) (! TYPE_SIGNED (t) \
>>>>         ? (t) -1 \
>>>>         : ~ (~ (t) 0 << (sizeof (t) * CHAR_BIT - 1))))
>> The last line of this macro has UB due to signed integer overflow in
>> the << operation.
> 
> No it doesn't.  ~ (t) 0 evaluates to -1, and -1 << 31 does not
> overflow.

C99 states this (6.5.7 paragraph 4)

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits
are filled with  zeros. If E1 has an unsigned type, the value of the
result is E1 × 2^E2 , reduced modulo one more than the maximum value
representable in the result type. If E1 has a signed type and
nonnegative value, and E1 × 2^E2 is representable in the result type,
then that is the resulting value; otherwise, the behavior is undefined.

In other words, the problem is not about overflow, but about undefined
behavior.

-- 
Eric Blake   ebl...@redhat.com    +1-801-349-2682
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to