What is the correct type for array indexes in C?

2019-01-06 14:55发布

What type for array index in C99 should be used? It have to work on LP32, ILP32, ILP64, LP64, LLP64 and more. It doesn't have to be a C89 type.

I have found 5 candidates:

  • size_t
  • ptrdiff_t
  • intptr_t / uintptr_t
  • int_fast*_t / uint_fast*_t
  • int_least*_t / uint_least*_t

There is simple code to better illustrate problem. What is the best type for i and j in these two particular loops. If there is a good reason, two different types are fine too.

for (i=0; i<imax; i++) {
        do_something(a[i]);
}
/* jmin can be less than 0 */
for (j=jmin; j<jmax; j++) {
        do_something(a[j]);
}

P.S. In the first version of question I had forgotten about negative indexes.

P.P.S. I am not going to write a C99 compiler. However any answer from a compiler programmer would be very valuable for me.

Similar question:

8条回答
成全新的幸福
2楼-- · 2019-01-06 15:17

If you know the maximum length of your array in advance you can use

  • int_fast*_t / uint_fast*_t
  • int_least*_t / uint_least*_t

In all other cases i would recommend using

  • size_t

or

  • ptrdiff_t

depending on weather you want to allow negative indexes.

Using

  • intptr_t / uintptr_t

would be also safe, but have a bit different semantics.

查看更多
做自己的国王
3楼-- · 2019-01-06 15:23

I think you should use ptrdiff_t for the following reasons

  • Indices can be negative (thus all unsigned types, including size_t, are out of question)
  • The type of p2 - p1 is ptrdiff_t. The type of i in the reverse thing, *(p1 + i), should be that type too (notice that *(p + i) is equivalent to p[i])
查看更多
登录 后发表回答