简体   繁体   中英

Printf in unsigned short int and unsigned int using %d

Why in second printf when using %d I am not getting -1?

#include<stdio.h>
int main(){
    unsigned int u=-1;
    unsigned short int y=-1;
    printf("%d %u\n",u,u);
    printf("%d %u",y,y);
}

Assuming int is 32-bit, short is 16-bit, and the architecture uses two's complement: When you set y=-1 the conversion from signed to unsigned yields 65535 . When y is passed to printf it is promoted back to int , but this time the value 65535 is representable, thus printf will print 65535 .

The variable u is declared as having the type unsigned int .

unsigned int u=-1;

So you may not use the conversion specifier %d with this variable because the value of the u is not representable in an object of the type int . You have to use the conversion specifier %u .

As for your question then the variable y has the type unsigned short and its value as an unsigned value after the integer promotion to the type int can be represented in an object of the type int . So the positive value is outputted.

In this declaration

unsigned short int y=-1;

the integer constant -1 is converted to the type unsigned short and if your compiler supports the 2's complement representation of integers the converted value represents the positive value USHRT_MAX.

Because you have defined y as unsigned short . Because -1 is absolutely a signed int so the compiler will not store it into y as -1 instead it will be stored as 65535 which is the overflow result of -1 . ie unsigned short range 65536 - 1 .

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