The Linux Page

C printf(3) for int, long and long long that works every time

Of Note: This only applies to C99, not C++.

I learned something quite interesting today and wanted to keep a note of it.

Whenever I use a printf() with a format such as %ld and try to compile my code on "many" different platforms, I often get warnings on another one.

The fact is that an int, a long, a long long, an int32_t, int64_t all use a different combination depending on your platform and whether you're running in 32 or 64 bit.

So, the answer to this problem are the #define found in the inttypes.h header file:

PRId8
PRId16
PRId32
PRId64

These entries are used after the % in the format strings. They are strings themselves, so you put them between your % and the rest of your string such as:

printf("The total of %" PRId64 " dollars is the maximum spent this year.\n");

As you can see, that totally eliminate the guessing game... Will PRId64 be %d, %ld, or %lld? The header defines the correct value for you. (oh! year! don't add the "d" afterward!)

In PRId64, replace the 'd' with 'i', 'o', 'u', 'x', 'X' and you'll get the corresponding effect as expected.

They also include PRI... entries for two special types: uintmax_t and uintptr_t.

And if you are one of those people who like to use scanf(), you have the SCN... entries at your disposal.

Really, to see all the possibilities, check out your inttypes.h. Just in case, I made a copy of my current version here (click on the link below to see the file.)