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 following d, i, o, u, x, or x conversion specifier applies size_t or corresponding signed integer type argument; or following n conversion specifier applies pointer signed integer type corresponding size_t argument. c11dr §7.21.6.1 7

should read as

  1. "z specifies following d ... conversion specifier applies size_t or corresponding signed integer type argument ... "(both types) , "z specifies following u ... conversion specifier applies size_t or corresponding signed integer type argument ..." (both types)

or

  1. "z specifies following d ... conversion specifier applies corresponding signed integer type argument ..." (signed type only) , "z specifies following u ... conversion specifier applies size_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

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -