[Top][All Lists]

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

Re: [Tinycc-devel] wrong preprocessor shift operation

From: Dave Dodge
Subject: Re: [Tinycc-devel] wrong preprocessor shift operation
Date: Tue, 30 Dec 2008 18:07:41 -0500
User-agent: Mutt/1.5.17 (2008-05-15)

On Tue, Dec 30, 2008 at 05:32:57PM +0100, grischka wrote:
> Christian Jullien wrote:
>>      printf("fails %08x\n", (~0) >> 1);

> fails ffffffff

> Maybe gcc is not correct but then I need an exact explanation why ;)

0 has type int.  On x86 the representation is 32 value bits set to
zero, with no padding bits.

~0 flips all of the bits of the representation, producing an int with
value -1.

(~0) >> 1 is a right-shift of a signed integer with negative value,
which is an implementation-defined operation.  On x86, this is usually
implemented with the SAR instruction, which divides by 2 with rounding
toward -infinity.  -1/2 rounded toward -infinity is -1, so the value
is unchanged.

This then passes int -1 to a printf specifier that expects unsigned
int.  Since the value is negative and cannot be represented by
unsigned int, you get undefined behavior and any result is allowed.

I believe in this case, the representation of int -1 is reinterpreted
as an unsigned int, producing the printed value ffffffff.  But really,
the test itself is fundamentally broken.

                                                  -Dave Dodge

reply via email to

[Prev in Thread] Current Thread [Next in Thread]