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;
Is this correct?
I know we should also likely be using something like memset
, but let's avoid that entirely. I'm only asking about the type
The answer to the OP's question is yes, size_t is most appropriate for the example code, where no pointer values are being subtracted from each other, and there are no cross-compiler/library compatibility issues around
malloc
behaviors. Regardless of difference in heap managers, in C, an array can beSIZE_MAX
bytes in length and that requires asize_t
to represent it. Nothing in the standard requires a heap manager to be able to allocate all of a process memory space in the heap, or to allocate up toSIZE_MAX
bytes for that matter, but an array can beSIZE_MAX
in length, hencesize_t
is appropriate.Even if
n
is signed, using aptrdiff_t
fori
isn't going to help, as the initiali < n
test will fail anyway, ifn
is negative, becausei
is initialized to zero. There is no index intoi
that asize_t
index cannot access. The only place thatptrdiff_t
is needed, is where you subtract one pointer value from another, and the OP isn't asking about that.