I'm currently using a explicit cast to long and using %ld
for printing pid_t
, is there a specifier such as %z
for size_t
for pid_t
?
If not what the best way of printing pid_t
?
Join Stack Overflow to learn, share knowledge, and build your career.
I'm currently using a explicit cast to long and using %ld
for printing pid_t
, is there a specifier such as %z
for size_t
for pid_t
?
If not what the best way of printing pid_t
?
There's no such specifier. I think what you're doing (casting the pid_t
to long
and printing it with "%ld"
) is fine; you could use an even wider int type, but there's no implementation where pid_t
is bigger than long
and probably never will be.
printf
with your own spec for pid_t
, check out this page: stackoverflow.com/questions/9260170/…
– Mad Physicist
Dec 12 '13 at 1:59
long
is 64-bit, printing with a "%ld"
will certainly cause issues.
– chux - Reinstate Monica
Dec 23 '19 at 18:00
With integer types lacking a matching format specifier as in the case of pid_t
, yet with known sign-ness1, cast to widest matching signed type and print.
If sign-ness is not known for other system type, cast to the widest unsigned type or alternate opinion
pid_t pid = foo();
// C99
#include <stdint.h>
printf("pid = %jd\n", (intmax_t) pid);
Or
// C99
#include <stdint.h>
#include <inttypes.h>
printf("pid = %" PRIdMAX "\n", (intmax_t) pid);
Or
// pre-C99
pid_t pid = foo();
printf("pid = %ld\n", (long) pid);
1
The pid_t
data type is a signed integer type which is capable of representing a process ID.
uintmax_t
and printing with %ju
will print all negative values incorrectly, whereas casting to intmax_t
and printing with %jd
will only print values > INTMAX_MAX
incorrectly. (Then again, situations in which one really doesn't know whether a type includes negative values are quite rare.)
– Jim Balter
Dec 23 '19 at 23:46
intmax_t
as small values are more common, yet conversion signed integer to uintmax_t
is more narrowly defined which does not lose info (hence my preference) than unsigned integer to intmax_t
can. Choose your poison .
– chux - Reinstate Monica
Dec 24 '19 at 0:12