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
mallocbehaviors. Regardless of difference in heap managers, in C, an array can beSIZE_MAXbytes in length and that requires asize_tto 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_MAXbytes for that matter, but an array can beSIZE_MAXin length, hencesize_tis appropriate.Even if
nis signed, using aptrdiff_tforiisn't going to help, as the initiali < ntest will fail anyway, ifnis negative, becauseiis initialized to zero. There is no index intoithat asize_tindex cannot access. The only place thatptrdiff_tis needed, is where you subtract one pointer value from another, and the OP isn't asking about that.