c - 如何使用 printf 系列可移植地打印 size_t 变量?

标签 c printf

我有一个 size_t 类型的变量,我想使用 printf() 打印它.我使用什么格式说明符来便携地打印它?

在 32 位机器中,%u似乎是对的。我用 g++ -g -W -Wall -Werror -ansi -pedantic 编译,并且没有任何警告。但是当我在 64 位机器上编译该代码时,它会产生警告。

size_t x = <something>;
printf("size = %u\n", x);

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

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

问题是,我如何编写代码,以便它在 32 位和 64 位机器上编译时都没有警告?

编辑:作为一种解决方法,我想一个答案可能是将变量“转换”为一个足够大的整数,比如 unsigned long , 并使用 %lu 打印.这在两种情况下都有效。我正在寻找是否有任何其他想法。

最佳答案

使用 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

关于c - 如何使用 printf 系列可移植地打印 size_t 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2524611/

相关文章:

c - 如何将int类型转换为ieee754?

c++ - 前置或附加到每个 printf 调用

ios - 循环不会像我希望的那样在 objective-c 中更改标签

c - 文件无故崩溃

c++ - 使用 fgets() 从文件读取会导致 "Access Violation reading from address..."c++

c - 打印出十六进制奇怪输出的值?

C printf %a 和 %La

java - 像 Java 一样格式化 Python float

c - 延迟之前的 printf 在 C 中不起作用

C scr_restore 函数不工作