简体   繁体   中英

Comparison of signed int and unsigned short in c++

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM