问题
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
?
回答1:
There's no such specifier. I think what you're doing 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.
回答2:
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, cast to the widest unsigned type.
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.
来源:https://stackoverflow.com/questions/20533606/what-is-the-correct-printf-specifier-for-printing-pid-t