There isn't a fully portable way to do it, and it is a nuisance.
C99 provides a mechanism for built-in types like size_t
with the %zu
notation (and there are some extra, similar qualifiers).
It also provides the <inttypes.h>
header with macros such as PRIX32 to define the correct qualifier for printing a 32-bit hexadecimal constant (in this case):
printf("32-bit integer: 0x%08" PRIX32 "\n", var_of_type_int32_t);
For the system-defined types (such as those defined by POSIX), AFAIK, there is no good way to handle them. So, what I do is take a flying guess at a 'safe' conversion and then print accordingly, including the cast, which is what you illustrate in the question. It is frustrating, but there is no better way that I know of. In case of doubt, and using C99, then conversion to 'unsigned long long' is pretty good; there could be a case for using a cast to uintmax_t
and PRIXMAX or equivalent.
Or, as FUZxxl reminded me, you can use the modifier j
to indicate a 'max' integer type. For example:
printf("Maximal integer: 0x%08jX\n", (uintmax_t)var_of_type_without_format_letter);
Use the z
modifier:
size_t x = ...;
ssize_t y = ...;
printf("%zu\n", x); // prints as unsigned decimal
printf("%zx\n", x); // prints as hex
printf("%zd\n", y); // prints as signed decimal
Best Answer
To print
off_t
:To print
size_t
:To print
ssize_t
:See 7.19.6.1/7 in the C99 standard, or the more convenient POSIX documentation of formatting codes:
http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html
If your implementation doesn't support those formatting codes (for example because you're on C89), then you have a bit of a problem since AFAIK there aren't integer types in C89 that have formatting codes and are guaranteed to be as big as these types. So you need to do something implementation-specific.
For example if your compiler has
long long
and your standard library supports%lld
, you can confidently expect that will serve in place ofintmax_t
. But if it doesn't, you'll have to fall back tolong
, which would fail on some other implementations because it's too small.