Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the %zu specifier required for printf?

We are using C89 on an embedded platform. I attempted to print out a size_t, but it did not work:

#include <stdio.h>
int main(void) {
    size_t n = 123;
    printf("%zu\n",n);
    return 0;
}

Instead of 123, I got zu.
Other specifiers work correctly.

If size_t exists shouldn't zu also be available in printf?
Is this something I should contact my library vendor about, or is a library implementation allowed to exclude it?

like image 956
Trevor Hickey Avatar asked Dec 21 '16 13:12

Trevor Hickey


People also ask

What is %zu in printf?

The correct way to print size_t variables is use of “%zu”. In “%zu” format, z is a length modifier and u stand for unsigned type. The following is an example to print size_t variable.

What do I need to include to use printf?

To use printf() in our program, we need to include stdio. h header file using the #include <stdio. h> statement.

Which format specifier defines character in printf () function?

If printf() contains more than one argument then the format of the output is defined using a percent (%) character followed by a format description character. A signed integer uses the %d conversion control characters, an unsigned integer %u.


1 Answers

If size_t exists shouldn't zu also be available in printf?

size_t existed at least since C89 but the respective format specifier %zu (specifically the length modifier z) was added to the standard only since C99.

So, if you can't use C99 (or C11) and had to print size_t in C89, you just have to fallback to other existing types, such as:

printf("%lu\n", (unsigned long)n);
like image 163
P.P Avatar answered Sep 21 '22 08:09

P.P