Home > Net >  Printf in unsigned short int and unsigned int using %d
Printf in unsigned short int and unsigned int using %d

Time:10-29

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);
}

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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. i.e. unsigned short range 65536 - 1.

  • Related