1. Home >
  2. Apps >
  3. Groups >

What's the output of this program?

Question asked by Leo in #Coffee Room on Sep 10, 2009
Leo
Leo · Sep 10, 2009
Rank B3 - LEADER
If you need a challenge then solve this, don't expect answer from me. I always stay busy. See what will be the answer of following code and why?

int main()
{
signed int x=-1;
unsigned int y=1;
if(x<y)
puts("Y is greater");
else
puts("X is greater");
return 0;
}

Whenever i will return i will post answer. Try to figure out what is problem till then.


WE HATE PIRACY.
Posted in: #Coffee Room
Divisha Madupalli
Divisha Madupalli · Feb 12, 2020
Rank C2 - EXPERT

If one operand is unsigned, then the other operand is converted by the compiler implicitly into unsigned if its type is signed and then the comparison takes place.

It is because the binary representation for negative values assumes the highest bit has value of 1. E.g., all negative 8-bit values look like 1________.

8-bit value for -1 is 1111 1111.

Hence, the very same binary 1111 1111 for unsigned is 255. So, the value can be interpreted in two different ways, depending on if it is signed or not.

This is done due to the errors in the C compiler in the prior versions.


You must log-in or sign-up to reply to this post.

Click to Log-In or Sign-Up