#include<stdio.h>
int main()
{
unsigned short a=-1;
printf("%d",a);
return 0;
}
- This is giving me output 65535. why?
- When I increased the value of a in negative side the output is (2^16-1=)65535-a.
-
I know the range of unsigned short int is 0 to 65535.
But why is rotating in the range 0 to 65535.What is going inside?#include<stdio.h> int main() { unsigned int a=-1; printf("%d",a); return 0; } - Output is -1.
- %d is used for signed decimal integer than why here it is not following the rule of printing the largest value of its(int) range.
- Why the output in this part is -1?
-
I know %u is used for printing unsigned decimal integer.
Why the behavioral is undefined in second code and not in first.?
This I have compiled in gcc compiler. It’s a C code
On my machine sizeof short int is 2 bytes and size of int is 4 bytes.
In your implementation, short is 16 bits and int is 32 bits.
First, -1 is converted to
unsigned short. This results in the value 65535. For the precise definition see the standard “integer conversions”. To summarize: the value is taken moduloUSHORT_MAX+1.This value 65535 is assigned to
a.Then for the
printf, which uses varargs, the value is promoted back toint. varargs never pass integer types smaller than int, they’re always converted to int. This results in the value 65535, which is printed.First line, same as before but modulo
UINT_MAX+1.ais 4294967295.For the printf,
ais passed as anunsigned int. Since%drequires anintthe behavior is undefined by the C standard. But your implementation appears to have reinterpreted the unsigned value 4294967295, which has all bits set, as as a signed integer with all-bits-set, i.e. the two’s-complement value -1. This behavior is common but not guaranteed.