保证`long`与`size_t`一样宽 [英] Was `long` guaranteed to be as wide as `size_t`
问题描述
在寻找 unsigned long
足以容纳 size_t
的证据以作为对 printf
的论据的证据时,我遇到了两个事实(oids.
When looking for evidence of unsigned long
being enough to hold size_t
for the purpose of being argument to printf
I ran into two fact(oid)s.
首先,有一个答案指出, long
的确不能保证足够大 size_t
.另一方面,我看到了这个答案,建议使用 printf(%lu",(无符号长)x)
在C99之前的版本中, x
的大小为 size_t
.
First there's this answer stating that long
is indeed not guaranteed to be large enough for size_t
. On the other hand I saw this answer suggesting to use printf("%lu", (unsigned long)x)
in pre C99, x
being of size_t
.
所以问题是您可以假设还是可以保证 long
足以在 C99之前的版本中容纳 size_t
.另一个问题是,是否可以保证 size_t
可以适用于任何其他标准化整数类型(除了明显的例外,例如 ssize_t
, ptrdiff_t
等).
So the question is could you assume or were you guaranteed that long
were enough to hold size_t
in pre C99. The other question is whether there exists any guarantee that size_t
would fit in any of the other standardized integer types (except the obvious exceptions like ssize_t
, ptrdiff_t
and such).
推荐答案
没有这样的保证.
虽然通常对于 long
和 size_t
具有相同的大小是实现的,但并非总是如此.如注释中所述,Windows 64位的 long
和 size_t
具有不同的大小.
While it is common for implementation to have same size for long
and size_t
, it is not always the case. As put in the comments Windows 64-bit have different size for long
and size_t
.
还要注意,实现的 SIZE_MAX
的最小值是 65535
,而 ULONG_MAX
的最小值是 4294967295
( LONG_MAX
的 2147483647
).(请注意, SIZE_MAX
随C99一起出现.)这意味着 size_t
可以保证至少为16位,但 unsigned long
/长
保证至少为32位.
Also notice that the minimum value of SIZE_MAX
for an implementation is 65535
while the minimum value of ULONG_MAX
is 4294967295
(2147483647
for LONG_MAX
). (Note that SIZE_MAX
appeared with C99.) It means that size_t
is guaranteed to be at least 16-bit but unsigned long
/ long
are guaranteed to be at least 32-bit.
在此答案之后,问题已经改变了一点……所以:
Question has changed a little bit after this answer... So:
所以问题是您是否可以假设还是可以保证足够长的时间来容纳C99之前的size_t.
即使在C89中也没有这样的保证. long
可以是32位,而 size_t
可以是64位.(请参见上面Windows 64位中带有MSVC的C89示例.)
There is no such guarantee even in C89. long
can be 32-bit and size_t
64-bit. (See C89 example with MSVC in Windows 64-bit above.)
另一个问题是,是否可以保证size_t可以适合任何其他标准化整数类型(明显的例外,例如ssize_t,ptrdiff_t等).
同样,标准不提供此类保证. size_t
是另一个标准无符号整数类型的别名(并且它不能是扩展整数类型,因为C89没有扩展整数类型).
Again there is no such guarantee by the Standard. size_t
is an alias for another standard unsigned integer type (and it cannot be an extended integer type as C89 does not have extended integer types).
这篇关于保证`long`与`size_t`一样宽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!