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);
}
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. i.e. unsigned short range 65536 - 1.
unsigned short range is not set in stone, but it's never 65536 - 1. [0, 65536) ([0, 65535]) is possible.thoughunsigned short range is [0, 65,535] which means 65536 possibilities. so because -1 is stored in Two's complement in the memory it's stored like that 0b11111111 which will be interpreted as 65,535 when dealing with it as unsigned value.unsigned short range may be [0,65535]. It's at least 16 bits but it can be wider. What I mainly opposed was "unsigned short range 65536 - 1" which is a very strange way of describing ranges.
%huand%hdto printshortaccurately.