为了遍历数组,我们应该使用size_t还是ptrdiff_t? [英] For iterating though an array should we be using size_t or ptrdiff_t?
问题描述
在此博客中Andrey Karpov题为关于size_t
和ptrdiff_t
" 他展示了一个例子,
In this blog entry by Andrey Karpov entitled, "About size_t
and ptrdiff_t
" he shows an example,
for (ptrdiff_t i = 0; i < n; i++)
a[i] = 0;
但是,我不确定这是否正确,看来应该是
However, I'm not sure if that's right, it seems that should be
for (size_t i = 0; i < n; i++)
a[i] = 0;
这正确吗?
我知道我们也应该使用memset
之类的东西,但让我们完全避免这种情况.我只问类型
I know we should also likely be using something like memset
, but let's avoid that entirely. I'm only asking about the type
推荐答案
In a blog post, I argue that you should always refrain from allocating memory blocks larger than PTRDIFF_MAX
(*), because doing so will make compilers such as Clang and GCC generate nonsensical code even if you do not subtract pointers to that block in a way that causes the result to overflow.
(*)即使malloc
成功传递给它,它的值也大于PTRDIFF_MAX
.问题的症结在于,GCC和Clang仅生成与这样的malloc
链接时正确运行的代码,而Glibc提供的malloc
函数没有实现此限制.
(*) Even if malloc
succeeds when you pass it a value larger than PTRDIFF_MAX
. The crux of the problem is that GCC and Clang only generate code that behaves correctly when linked with such a malloc
, but Glibc provides a malloc
function that does not implement this limitation.
如果您遵循该约束(我鼓励您这样做:这是博客文章的内容),那么两种类型都同样正确.
If you follow that constraint (which I encourage you to: that's the message of the blog post), then both types are equally correct.
这就是说,由于仅需要表示正偏移量,因此size_t
是您示例中的自然选择.
This said, since only positive offsets need to be represented, size_t
would be the natural choice in your example.
这篇关于为了遍历数组,我们应该使用size_t还是ptrdiff_t?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!