怎样才能打印为size_t变量可移植使用printf系列? [英] How can one print a size_t variable portably using the printf family?
问题描述
我型为size_t
的变量,我想用的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?
在32位机,%U
似乎是正确的。我用g ++的-g -W -Wall -ansi -Werror -pedantic编制,也没有警告。但是,当我编译code在64位机,它产生的警告。
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'
警告消失,如预期,如果我更改为鲁%
。
现在的问题是,我怎么能写code,所以它编译于32位和64位的机器没有警告的?
The question is, how can I write the code, so that it compiles warning free on both 32- and 64- bit machines?
编辑:我猜一个答案可能是中投变到无符号长
,和使用打印%禄
。这将在这两种情况下工作。我找是否有任何其他的想法。
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("%zu\n", x); // prints as unsigned decimal
printf("%zx\n", x); // prints as hex
printf("%zd\n", y); // prints as signed decimal
这篇关于怎样才能打印为size_t变量可移植使用printf系列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!