How can one print a size_t variable portably using the printf family? How can one print a size_t variable portably using the printf family? c 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("%zu\n", x);  // prints as unsigned decimalprintf("%zx\n", x);  // prints as hexprintf("%zd\n", y);  // prints as signed decimal


Looks like it varies depending on what compiler you're using (blech):

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


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

size_t foo;...printf("foo = %lu\n", (unsigned long) foo);

For C99 and later, use %zu:

size_t foo;...printf("foo = %zu\n", foo);