Reputation: 31
What are the format specifiers to use for printf when dealing with types such as int32_t, uint16_t and int8_t, etc.?
Using %d, %i, etc. will not result in a portable program. Is using the PRIxx macros the best approach?
Upvotes: 3
Views: 1587
Reputation: 881403
Yes, if you're using the new types, you really should be using the new format specifiers.
That's the best way to do it since the implementation has already done the grunt work of ensuring the format strings will be correct for the types.
So, for example:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main (void) {
int32_t i32 = 40000;
printf ("%d\n", i32); // might work.
printf ("%" PRId32 "\n", i32); // will work.
return 0;
}
shows both ways of doing it.
However, there's actually no guarantee that the first one will do as you expect. On a system with 16-bit int
types for example, you may well get a different value.
Upvotes: 0
Reputation: 61713
Is using the PRIxx macros the best approach?
As far as I know, yes.
Edit: another solution is to cast to a type that is at least as wide as the one you want to print. For example int
is at least 2 bytes wide, to can print a int16_t
with printf("%d\n", (int)some_var)
.
Upvotes: 3