comparison b/w signed and unsigned integers .... reasons???

Oct 19, 2011 at 8:44pm
int main()
{
unsigned int u = 5;
int i = -1;
for( ; i <= u; i++)
cout<<"intelligent";
}

y program doesnt show any results??? dont say a signed integer cant compare with unsigned ... i want reason!!!!
Oct 19, 2011 at 10:20pm
unsigned and signed types are different ways to interpret data.

For example, if you have the raw data 0xFFFFFFFF, this can be interpretted one of two ways:

1) signed, it is interpretted as -1
2) unsigned, it is interpretted as 4294967295

When you compare signed 'i' with unsigned 'u', the compiler gets confused because it doesn't know how you want to compare the different types. Do you want to compare them as signed variables? or unsigned?

As a result, it (should) give you a warning. Then it'll do whatever it feels is best, which in this case would be treating them both as unsigned (since it's "larger").

The end result is that you are comparing unsigned i (4294967295) to unsigned u (5). Since i is much larger than u, the loop body never executes.
Oct 19, 2011 at 10:33pm
I like to add to that, why did you declare i outside the for loop?

1
2
3
4
for(int i = -1 ; i < 5 ; i++)
{
     cout << "intelligent";
}


of course your output would look like this when it works the way you are trying to get it:

intelligentintelligentintelligentintelligentintelligentintelligent
Oct 20, 2011 at 6:48pm
thanks Disch!!!! really appreciate it!!!
Topic archived. No new replies allowed.