Passing a negative to "%hu" in C
12,769
It will print 65535
"%hu"
is an unsigned short int
which is 16 bit.
-1
is "all-ones", e.g. 0xffff.ffff
, but since it gets converted to short it is only 0xffff
. Which is 65535
as unsigned.
Author by
Александар Стјепановић
Updated on June 04, 2022Comments
-
Александар Стјепановић almost 2 years
I can't get it to work in CodeBlocks What will this code print? :
printf( "%hu" , ‐1 );
-
chux - Reinstate Monica almost 9 yearsNote:
unsigned short int
which is 16 bit is often true, but not defined by C. C definesunsigned short int
to be at least 16 bit.-1 is "all-ones"
is also very often true (2's complement) but not defined by C to be so. -
Support Ukraine almost 9 years@chux - True. In principle we can't tell what the code would print without knowledge of the system being used. However, I'm confident that most systems out there uses 16 bits for shorts and 2's complement representation for signed integers.