Date: Wed, 15 May 2002 16:18:38 -0400 (EDT) From: Thomas David Rivers <rivers@dignus.com> To: audit@FreeBSD.ORG, knu@iDaemons.org Cc: current@FreeBSD.ORG Subject: Re: moused(8): char signed-ness problem with gcc 3.1 Message-ID: <200205152018.g4FKIc946014@lakes.dignus.com> In-Reply-To: <86sn4t8fzp.wl@archon.local.idaemons.org>
next in thread | previous in thread | raw e-mail | index | archive | help
>
> I observed gcc 2.95.4 and gcc 3.1 interpret (or maybe optimize) the
> following code differently (CFLAGS=-O):
>
> int main(void)
> {
> unsigned char i = 127;
> printf("%d\n", ((char)(i << 1)) / 2);
> return 0;
> }
>
> gcc 2.95.4 says it's -1, whereas gcc 3.1 says it's 127. On FreeBSD
> char should be signed, so I suspect it's a (optimization) bug of gcc
> 3.1 which should be fixed. Or we'll have to do a mass audit of the
> whole src tree to check and fix the similar expressions.
Let's examine the what the "right" answer should be:
First - in the expression (i << 1) - the unsigned char `i' will
be promoted to a signed int through the correct integral promotion
rules, then left-shifted 1 bit. The result of that is an int.
So - this becomes:
((char)(254)) / 2 ;
The expression:
(char)(254)
is then also promoted to int when it participates
in the division operation. So, the value 254 is
converted into a (signed) char, and then converted
to an int. Converting 254 to a signed character
should result in an integer value of -2.
Then, -2 / 2 becomes -1.
If characters were unsigned by default, you do
get the value 127...
So - yes - it seems gcc 3.1 does have a problem...
- Dave Rivers -
--
rivers@dignus.com Work: (919) 676-0847
Get your mainframe programming tools at http://www.dignus.com
To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-audit" in the body of the message
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?200205152018.g4FKIc946014>
