c – How can one print a size_t variable portably using the printf family?

c – How can one print a size_t variable portably using the printf family?

Use the z modifier:

size_t x = ...;
ssize_t y = ...;
printf(%zun, x);  // prints as unsigned decimal
printf(%zxn, x);  // prints as hex
printf(%zdn, y);  // prints as signed decimal

Looks like it varies depending on what compiler youre using (blech):

…and of course, if youre using C++, you can use cout instead as suggested by AraK.

c – How can one print a size_t variable portably using the printf family?

For C89, use %lu and cast the value to unsigned long:

size_t foo;
...
printf(foo = %lun, (unsigned long) foo);

For C99 and later, use %zu:

size_t foo;
...
printf(foo = %zun, foo);

Leave a Reply

Your email address will not be published.