I reading a C book. To print out a memory address of a variable, sometimes the book uses:
printf("%u\n",&n);
Sometimes, the author wrote:
printf("%d\n",&n);
The result is always the same, but I do not understand the differences between the two (I know %u for unsigned).
Can anyone elaborate on this, please?
Thanks a lot.
%utreats the integer as unsigned, whereas%dtreats the integer as signed. If the integer is between 0 anINT_MAX(which is 231-1 on 32-bit systems), then the output is identical for both cases.It only makes a difference if the integer is negative (for signed inputs) or between
INT_MAX+1andUINT_MAX(e.g. between 231 and 232-1). In that case, if you use the%dspecifier, you’ll get a negative number, whereas if you use%u, you’ll get a large positive number.Addresses only make sense as unsigned numbers, so there’s never any reason to print them out as signed numbers. Furthermore, when they are printed out, they’re usually printed in hexadecimal (with the
%xformat specifier), not decimal.You should really just use the
%pformat specifier for addresses, though—it’s guaranteed to work for all valid pointers. If you’re on a system with 32-bit integers but 64-bit pointers, if you attempt to print a pointer with any of%d,%u, or%xwithout thelllength modifier, you’ll get the wrong result for that and anything else that gets printed later (becauseprintfonly read 4 of the 8 bytes of the pointer argument); if you do add thelllength modifier, then you won’t be portable to 32-bit systems.Bottom line: always use
%pfor printing out pointers/addresses:The exact output format is implementation-defined (C99 §7.19.6.1/8), but it will almost always be printed as an unsigned hexadecimal number, usually with a leading
0x.