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

Arun picture Arun · Mar 26, 2010 · Viewed 300.9k times · Source

I have a variable of type size_t, and I want to print it using printf(). What format specifier do I use to print it portably?

In 32-bit machine, %u seems right. I compiled with g++ -g -W -Wall -Werror -ansi -pedantic, and there was no warning. But when I compile that code in 64-bit machine, it produces warning.

size_t x = <something>;
printf("size = %u\n", x);

warning: format '%u' expects type 'unsigned int', 
    but argument 2 has type 'long unsigned int'

The warning goes away, as expected, if I change that to %lu.

The question is, how can I write the code, so that it compiles warning free on both 32- and 64- bit machines?

Edit: As a workaround, I guess one answer might be to "cast" the variable into an integer that is big enough, say unsigned long, and print using %lu. That would work in both cases. I am looking if there is any other idea.

Answer

Adam Rosenfield picture Adam Rosenfield · Mar 26, 2010

Use the z modifier:

size_t x = ...;
ssize_t y = ...;
printf("%zu\n", x);  // prints as unsigned decimal
printf("%zx\n", x);  // prints as hex
printf("%zd\n", y);  // prints as signed decimal