Re: moused(8): char signed-ness problem with gcc 3.1

Thomas David Rivers <[email protected]>
Newsgroups gmane.os.freebsd.devel.audit
Message-ID <[email protected]>
> 
> 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 -

--
[email protected]                        Work: (919) 676-0847
Get your mainframe programming tools at http://www.dignus.com

To Unsubscribe: send mail to [email protected]
with "unsubscribe freebsd-audit" in the body of the message
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.