Search code examples
c++compareunsignedsigned

Signed vs Unsigned comparison


#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.


Solution

  • 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).