How to print size_t variable portably?

Posted by ArunSaha on Stack Overflow See other posts from Stack Overflow or by ArunSaha
Published on 2010-03-26T15:52:25Z Indexed on 2010/03/26 16:03 UTC
Read the original article Hit count: 160

Filed under:
|

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++)

© Stack Overflow or respective owner

Related posts about c

    Related posts about c++