Signed vs Unsigned comparison

183 Views Asked by At
#include <iostream>

int main()
{
    signed int a = 5;
    unsigned char b = -5;
    unsigned int c = a > b;

    std::cout << c << std::endl;
}

This code prints 0.

Can anyone please explain what is happening here? I am guessing that compiler converts a and b to same type(unsigend int maybe) and compares them.

3

There are 3 best solutions below

1
On BEST ANSWER

Let's see how the computer stores the value b:
5 is 00000101, so -5 will be 11111011, so, when you convert it to unsigned char, it will became some positive number with value 11111011 in binary, which is larger than 00000101.
So, that's why a = 00000101 is smaller than b (0 means false).

0
On

It is printing 0 because a < b and 0 means false. The type of b is unsigned so it cannot hold negative numbers. Because of that -5 becomes 251 which is grater than 5.

0
On

Lets go to the third line in main c take the value of 0 because a is not greater than b. This is because in C zero is considered false and everything then else is true.

With regards to b. Most platforms store negative integers using 2s complement format. So when we negate an number we flip all the bits and add 1. So -5 unsigned become 0xfa which is greater than 5.