This is the mail archive of the
mailing list for the GCC project.
Re: signed comparison issue?
- From: Andrew Haley <aph-gcc at littlepinkcloud dot COM>
- To: Jason Parker <jparker at digium dot com>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Mon, 12 Nov 2007 20:44:40 +0000
- Subject: Re: signed comparison issue?
- References: <4738B9C4.firstname.lastname@example.org>
Jason Parker writes:
> I was recently testing some code, and could not figure out why an
> expression was evaluating as true. I switched from gcc-4.1 to
> gcc-4.2 (and then down to gcc-3.4), and suddenly it started
> evaluating as I would have expected. I was hoping that somebody
> could either confirm my suspicions that this is a bug, or explain
> why it may not be.
> The simplified code in question:
> int32_t dlen = 2147483647;
> if ((int32_t)(dlen + 8) > (int32_t)2147483647)
> It appears as though it is evaluating that expression as unsigned
> in gcc-4.1, and as signed in gcc-3.4 and gcc-4.2. If either side
> is changed to an unsigned type, then the block is correctly
> evaluated as unsigned in all versions tested. It may also be
> interesting to note that if "dlen + 8" is changed to "2147483647 +
> 8" or "dlen + dlen2" (where dlen2 is an int32_t set to 8), that the
> expression is correctly evaluated as signed.
Your program is undefined because it causes integer overflow:
dlen + 8 has no defined value in C. However, unsigned overflow
is defined by C as arithmetic modulo the wordlength. If you want
such arithmetic, you must use unsigned types.