当我阅读这篇文章时 article ,我遇到了这一段:
Similarly, don’t make any effort to cater to the possibility that long will be smaller than predefined types like size_t. For example, the following code is ok:
printf ("size = %lu\n", (unsigned long) sizeof array);
printf ("diff = %ld\n", (long) (pointer2 - pointer1));
1989 Standard C requires this to work, and we know of only one counterexample: 64-bit programs on Microsoft Windows. We will leave it to those who want to port GNU programs to that environment to figure out how to do it.
1989 标准 C 真的允许该代码吗?
最佳答案
提出的问题:
Does really the 1989 Standard C allow that code?
是的,如果我们所说的“允许”是指“这将编译并运行,做一些合理的事情并且不会触发未定义的行为”(而不是“这将做我想做的事”)。这两种情况略有不同。
对于size_t
,结果过大将被截断。对于 ptrdiff_t
,如果结果太大,则结果将由实现定义。
但是,最新版本的 Visual Studio (_MSC_VER >= 1800
) 支持 z
和 t
转换(C++11 所必需的)无论如何都支持),所以你可以使用:
size_t size;
printf("size = %zu\n", size);
ptrdiff_t diff;
printf("diff = %td\n", diff);
这也适用于其他系统(GNU、BSD、Darwin)。对于旧版本的 Visual Studio,有替代方案,但需要在不同的平台上使用不同的格式字符串。
关于 GNU 编码标准的说明
GNU 编码标准是针对 GNU 组织的,它有一些非常具体的目标,不太关心支持 Windows。我会对他们的编码标准持保留态度,除非您有特定的理由遵循它们(例如,您希望您的项目将来成为 GNU 项目)。
关于c - 在 GNU 系统中使用 printf 打印 size_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46083560/