Arun Arun - 6 months ago 24
C Question

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

I have a variable of type

, and I want to print it using
. What format specifier do I use to print it portably?

In 32-bit machine,
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

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

Edit: I guess one answer might be to "cast" the variable into an
unsigned long
, and print using
. That would work in both cases. I am looking if there is any other idea.


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