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

后端 未结 3 438
余生分开走
余生分开走 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:20

    Use of ptrdiff_t is ok since a[i] is translated as *(a + i).

    If you take two pointers, p1 and p2, it is encouraged that you use:

    ptrdiff_t d = p2 - p1; // Assuming p2 - p1 is valid.
    

    Given that, p2 == p1 + d, i.e. + ptrdiff_t is a valid expression. Whether ptrdiff_t or size_t is better as the index type is a matter of opinion and/or coding style used in a team.

提交回复
热议问题