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

Ashot
  • 10,807
  • 14
  • 66
  • 117
  • 1
    You might want to read about [integral conversions](http://en.cppreference.com/w/cpp/language/implicit_cast#Integral_conversions). – Some programmer dude Jun 25 '15 at 11:57
  • 1
    possible duplicate of [How do promotion rules work when the signedness on either side of a binary operator differ?](http://stackoverflow.com/questions/6770258/how-do-promotion-rules-work-when-the-signedness-on-either-side-of-a-binary-opera) – Cory Kramer Jun 25 '15 at 11:58
  • You may find an answer here: http://programmers.stackexchange.com/questions/175253/why-does-an-unsigned-int-compared-with-a-signed-character-turn-out-with-an-unexp – LBes Jun 25 '15 at 11:59
  • 1
    You can imagine `unsigned char b = -5` as first declare an `int` -5, and then assign it to `unsigned char`. The assignment just use the lower bits if -5, so it `b` will be 251 – Morrissss Jun 25 '15 at 12:00

3 Answers3

5

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

Chan Kha Vu
  • 9,834
  • 6
  • 32
  • 64
2

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.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
2

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.

doron
  • 27,972
  • 12
  • 65
  • 103