c - How to use "zd" specifier with `printf()`? -
looking clarification on using "zd"
printf()
.
certainly following correct c99 , later.
void print_size(size_t sz) { printf("%zu\n", sz); }
the c spec seems allow printf("%zd\n", sz)
depending on on how read:
7.21.6.1 fprintf
function
z
specifies followingd
,i
,o
,u
,x
, orx
conversion specifier appliessize_t
or corresponding signed integer type argument; or followingn
conversion specifier applies pointer signed integer type correspondingsize_t
argument. c11dr §7.21.6.1 7
should read as
- "
z
specifies followingd
... conversion specifier appliessize_t
or corresponding signed integer type argument ... "(both types) , "z
specifies followingu
... conversion specifier appliessize_t
or corresponding signed integer type argument ..." (both types)
or
- "
z
specifies followingd
... conversion specifier applies corresponding signed integer type argument ..." (signed type only) , "z
specifies followingu
... conversion specifier appliessize_t
" (unsigned type only).
i've been using #2 definition, not sure.
which correct, 1, 2, or else?
if #2 correct, example of type can use
"%zd"
?
printf
"%zd"
format expects argument of signed type corresponds unsigned type size_t
.
standard c doesn't provide name type or way determine is. if size_t
typedef unsigned long
, example, "%zd"
expects argument of type long
, that's not portable assumption.
the standard requires corresponding signed , unsigned types use same representation non-negative values representable in both types. footnote says meant imply they're interchangeable function arguments. this:
size_t s = 42; printf("s = %zd\n", s);
should work, , should print "42". interpret value 42
, of unsigned type size_t
, if of corresponding signed type. there's no reason that, since "%zu"
correct , defined, without resorting additional language rules. , "%zu"
works all values of type size_t
, including outside range of corresponding signed type.
finally, posix defines type ssize_t
in headers <unistd.h>
, <sys/types.h>
. though posix doesn't explicitly so, presumably ssize_t
signed type corresponding size_t
. if you're writing posix-specific code, "%zd"
(probably) correct format printing values of type ssize_t
.
Comments
Post a Comment