For iterating though an array should we be using size_t or ptrdiff_t?

后端 未结 3 436
余生分开走
余生分开走 2021-01-06 17:36

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;

3条回答
  •  灰色年华
    2021-01-06 18:19

    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 be SIZE_MAX bytes in length and that requires a size_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 to SIZE_MAX bytes for that matter, but an array can be SIZE_MAX in length, hence size_t is appropriate.

    Even if n is signed, using a ptrdiff_t for i isn't going to help, as the initial i < n test will fail anyway, if n is negative, because i is initialized to zero. There is no index into i that a size_t index cannot access. The only place that ptrdiff_t is needed, is where you subtract one pointer value from another, and the OP isn't asking about that.

提交回复
热议问题