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.
We should use “%zu” to print the variables of size_t length. We can use “%d” also to print size_t variables, it will not show any error. The correct way to print size_t variables is use of “%zu”. In “%zu” format, z is a length modifier and u stand for unsigned type.
C++ printf is a formatting function that is used to print a string to stdout. The basic idea to call printf in C++ is to provide a string of characters that need to be printed as it is in the program. The printf in C++ also contains a format specifier that is replaced by the actual value during execution.
We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.
for uint64_t type: #include <inttypes. h> uint64_t t; printf("%" PRIu64 "\n", t); you can also use PRIx64 to print in hexadecimal.
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
Looks like it varies depending on what compiler you're using (blech):
%zu
(or %zx
, or %zd
but that displays it as though it were signed, etc.)%Iu
(or %Ix
, or %Id
but again that's signed, etc.) — but as of cl v19 (in Visual Studio 2015), Microsoft supports %zu
(see this reply to this comment) ...and of course, if you're using C++, you can use cout
instead as suggested by AraK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With