Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

printf

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.

like image 911
Arun Avatar asked Mar 26 '10 15:03

Arun


People also ask

What is Size_t in printf?

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.

What format is used to print a string with the printf function?

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.

How do I printf a string?

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.

How do I print int64?

for uint64_t type: #include <inttypes. h> uint64_t t; printf("%" PRIu64 "\n", t); you can also use PRIx64 to print in hexadecimal.


2 Answers

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 
like image 189
Adam Rosenfield Avatar answered Oct 10 '22 08:10

Adam Rosenfield


Looks like it varies depending on what compiler you're using (blech):

  • gnu says %zu (or %zx, or %zd but that displays it as though it were signed, etc.)
  • Microsoft says %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.

like image 37
T.J. Crowder Avatar answered Oct 10 '22 08:10

T.J. Crowder