t variable portably using the printf family?

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 = %un", 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.


使用z修饰符:

size_t x = ...;
ssize_t y = ...;
printf("%zun", x);  // prints as unsigned decimal
printf("%zxn", x);  // prints as hex
printf("%zdn", y);  // prints as signed decimal

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.


    For C89, use %lu and cast the value to unsigned long :

    size_t foo;
    ...
    printf("foo = %lun", (unsigned long) foo);
    

    For C99 and later, use %zu :

    size_t foo;
    ...
    printf("foo = %zun", foo);
    
    链接地址: http://www.djcxy.com/p/12526.html

    上一篇: 常数0.0039215689代表什么?

    下一篇: 可变的可移植使用printf家族?