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
zspecifies followingd,i,o,u,x, orxconversion specifier appliessize_tor corresponding signed integer type argument; or followingnconversion specifier applies pointer signed integer type correspondingsize_targument. c11dr §7.21.6.1 7
should read as
- "
zspecifies followingd... conversion specifier appliessize_tor corresponding signed integer type argument ... "(both types) , "zspecifies followingu... conversion specifier appliessize_tor corresponding signed integer type argument ..." (both types)
or
- "
zspecifies followingd... conversion specifier applies corresponding signed integer type argument ..." (signed type only) , "zspecifies 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