Reputation: 305
I have a platform dependent type defined in my code:
typedef uint64_t myType;
However on some more limited platform, it might be 32 bits.
How do I printf
it?
As in, in the current situation, I can use %llu
, but if on another platform it's 32 bits, this is not the best idea.
I thought about using some macros, but would anyone know of a better way? I'd love to hear about some format specifier that could take the length from the next argument, for example.
Upvotes: 1
Views: 309
Reputation: 882586
Since you have platform-specific types, it should be easy enough to use platform-specific format strings as well, something like:
#ifdef USING_64_bits
typedef uint64_t myType;
#define MY_TYPE_FMT PRIu64
#else
typedef uint32_t myType;
#define MY_TYPE_FMT PRIu32
#endif
Then you can use it with:
myType var1 = 42, var2 = 99;
printf ("%6" MY_TYPE_FMT ", %019" MY_TYPE_FMT "\n", var1, var2);
The extraction of the %
from the format string allows you to insert other format specifiers dynamically, such as field widths and padding characters.
You'll also notice that I've avoided the %llu
-style format specifiers, you should be using the more targeted ones in inttypes.h
since the implementation will give you the correct one for your type.
Upvotes: 5
Reputation: 215567
Just cast it up to the largest-possible integer type matching the desired signedness and use the format for that, either:
printf("%jd", (intmax_t)x);
or:
printf("%ju", (uintmax_t)x);
(The question title asks for signed but the body is using unsigned examples, so I've covered both.)
This is a lot less ugly/more readable than using the PRI*
macros suggested in the other answer, and also works for types where you don't inherently know the right PRI
macro to use, like off_t
.
Upvotes: 5