Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tilde operator in C

 unsigned short int i = 0;
 printf("%u\n",~i);

Why does this code return a 32 bit number in the console? It should be 16 bit, since short is 2 bytes.

The output is 4,294,967,295 and it should be 65,535.

like image 815
Greyshack Avatar asked Dec 04 '22 04:12

Greyshack


1 Answers

%u expects an unsigned int; if you want to print an unsigned short int, use %hu.

EDIT

Lundin is correct that ~i will be converted to type int before being passed to printf. i is also converted to int by virtue of being passed to a variadic function. However, printf will convert the argument back to unsigned short before printing if the %hu conversion specifier is used:

7.21.6.1 The fprintf function
...
3 The format shall be a multibyte character sequence, beginning and ending in its initial shift state. The format is composed of zero or more directives: ordinary multibyte characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of which results in fetching zero or more subsequent arguments, converting them, if applicable, according to the corresponding conversion specifier, and then writing the result to the output stream.
...
7 The length modifiers and their meanings are:
...
h Specifies that a following d, i, o, u, x, or X conversion specifier applies to a short int or unsigned short int argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to short int or unsigned short int before printing); or that a following n conversion specifier applies to a pointer to a short int argument.

Emphasis mine.

So, the behavior is not undefined; it would only be undefined if either i or ~i were not integral types.

like image 113
John Bode Avatar answered Dec 24 '22 05:12

John Bode