Comparison of signed int and unsigned short in c++

-2

I know that when we compare signed with unsigned the compiler converts our signed values to unsigned and when we compare a short with int the compiler converts the smaller type to the larger one. But I wrote this code to check if we compared an signed int x=0xdeadbeef and unsigned short y=0xffff then after converting the unsigned short to int we should have 0x0000ffff in y at the comparison which should be smaller than the unsigned value of x. But my code does not go into the if condition that x is larger than y. Could someone explain to me why?

CODE SNIPPET:

#include<iostream>
using namespace std;

int main (){

        unsigned int x=0xDEADBEEF;
        unsigned short y= 0xFFFF;

        if((signed)x > y)
                cout<<"X is larger"<<endl;

  return 0;
}

When run the code does not print that "X is larger".

c++
unsigned
signed
asked on Stack Overflow Oct 16, 2017 by Ammar Bajwa • edited Oct 16, 2017 by Ammar Bajwa

1 Answer

0

When you type-cast x from unsigned to signed, it results in integer overflow. Note that signed int can hold a smaller positive value than an unsigned int would. So when an integer overflow happens, on most platforms, it starts acting like your car's odometer. i.e. once the int value exceeds the max it can store, it starts from the beginning. The 'beginning' in case of signed int on 32 bit system (int32) will be -2,147,483,648.

So in your case x is 0xDEADBEEF or 3,735,928,559. An unsigned int on 32 bit system can store this value. However, when it is type cast to signed, it results in an overflow and hence the above mentioned rule applies and converts that value to -1,588,444,912. Since it is negative, your condition in the if statement doesn't satisfy and hence your statement never gets printed.

answered on Stack Overflow Oct 16, 2017 by VHS

User contributions licensed under CC BY-SA 3.0