#include <stdio.h>
int main(void) {
int x = 5;
int y = &x;
printf("Signed Value of Y: %d \n", y);
printf("Unsigned Value of Y: %u", y);
return 0;
}
Since y is of int type, using %d gives a possibly-signed output, whereas %u gives an unsigned output. But y is of int type, so why does %u give unsigned output? Is there an implicit type conversion?
Effectively, a
printfcall is two separate things:In any function call, the arguments are prepared according to rules involving the argument types and the function declaration. They do not depend on the values of the arguments, including the contents of any string passed as an argument, and this is true of
printftoo.In a function call, the rules are largely (omitting some details):
...part of a function declaration or the called function is declared without specifying parameter types), some default promotions are applied. For integers, these are the integer promotions, which largely (omitting some details) convert types narrower thaninttoint. For floating-point,floatis promoted todouble.printfis declared asint printf(const char * restrict format, ...);, so all its arguments other than the format string correspond to....Inside
printf, the function examines its format string and attempts to perform the directives given in the format string. For example, if a directive is%g,printfexpects adoubleargument and takes bits from the place it expects adoubleargument to be passed. Then it interprets those bits as adouble, constructs a string according to the directive, and writes the string to standard output.For a
%dor%udirective,printfexpects anintor anunsigned intargument, respectively. In either case, it takes bits from the place it expects anintor anunsigned intargument to be passed. In all C implementations I am aware of, anintand anunsigned intargument are passed in the same place. So, if you pass anintargument but use%u,printfwill get the bits of anintbut will treat them as if they were the bits of anunsigned int. No actual conversion has been performed;printfis merely interpreting the bits differently.The C standard does not define the behavior when you do this, and a C implementation would be conforming to the standard if it crashed when you did this or if it processed the bits differently. You should avoid it.