This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: signed comparison issue?


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)
 >                 printf("blah\n");
 > 
 > 
 > 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.

Andrew.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]