系列可移植地打印

系列可移植地打印

本文介绍了如何使用 printf 系列可移植地打印 size_t 变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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 -Werror -ansi -pedantic 编译,没有警告.但是当我在 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
", x);

warning: format '%u' expects type 'unsigned int',
    but argument 2 has type 'long unsigned int'

正如预期的那样,如果我将其更改为 %lu,警告就会消失.

The warning goes away, as expected, if I change that to %lu.

问题是,我该如何编写代码,才能在 32 位和 64 位机器上编译时无警告?

The question is, how can I write the code, so that it compiles warning free on both 32- and 64- bit machines?

作为一种解决方法,我想一个答案可能是将变量转换"为一个足够大的整数,例如 unsigned long,然后使用 %lu.这在两种情况下都有效.我正在寻找是否有任何其他想法.

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.

推荐答案

使用 z 修饰符:

size_t x = ...;
ssize_t y = ...;
printf("%zu
", x);  // prints as unsigned decimal
printf("%zx
", x);  // prints as hex
printf("%zd
", y);  // prints as signed decimal

这篇关于如何使用 printf 系列可移植地打印 size_t 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 09:26