How to print size_t variable portably?
- by ArunSaha
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: I guess one answer might be to "cast" the variable into an unsigned long, and print using %lu. That would work in both cases. I am looking if there is any other idea.
(C, C++)