Riyash M H <riyash_mon@xxxxxxxxxxx> writes:
I am using gcc (GCC) 3.2.2 20030222 (Red Hat Linux 3.2.2-5). I have got a code which is not working according to what i expect. Can u tell me the reason behind that or is that a bug in the gcc version, i dont have another complier, i executed it with its "g++ " clone also. That too gave me the same results,
-----------------------------------------
int main(){ unsigned short i = 3; while(i > -1) printf("%u\n",i--); return 0; }
output: 3,2,1,0,65535,...............
-------------------------------------------
The reason is that "i" is promoted to "int" before the comparison, as the C standard mandates.
Hang on a moment here.
Shouldn't ((unsigned _whatever_) i > -1) ALWAYS be true, regardless of the size of _whatever_? It's particularly alarming, I think, that the complier seems to think that ((unsigned int) i > -1) is always _false_! It's almost like it's treating -1 as unsigned maxint, which does seem counterintuitive.
Wow. I just tried
int main(){ unsigned int i = 3; int j = -1; while(i > j) printf("%u\n",i--); return 0; }
And it had exactly the same result (nothing printed). From the assembly, it seems that the comparison will be unsigned if either side is unsigned! Not what I would have expected, but I guess what I should have expected, since the compiler has to live within the physical limits of the machine.
OTOH, I think that if the compiler's going to complain that the condition is always true in the case of the short integer, it should also caution that the condition is never true in the case of the integer, which it patently knows since it's not even including the loop!
Is there some flag to have the complier warn about signed-to-unsigned comparisons?
This is an incredible heads-up to those of us who have, perhaps, been a bit reckless mixing signed and unsigned integers!
Mario -- Whoever fights monsters should see to it that in the process he does not become a monster. -- Nietzsche