简体   繁体   中英

C Short to Int Conversion

I was given some code that looks like:

unsigned int x = 0xDEADBEEF;
unsigned short y = 0xFFFF;
if (x > (signed short) y)
    printf("Hello");

However, it's not true that x > y when y is casted to a signed short (and then implicitly converted to unsigned int in the comparison), it takes on the value of MAX_UINT. Why does this happen? Is y getting sign extended, or what else would cause such strange behavior?

unsigned to signed conversion for values that don't fit in the positive values of the signed type is implementation defined. Here, for your particular compiler, probably it turns out to be -1 and that then converted to unsigned is UINT_MAX .

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