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:
- size_t vs. uintptr_t
The context of this question if different though.
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.
I think you should use
ptrdiff_t
for the following reasonssize_t
, are out of question)p2 - p1
isptrdiff_t
. The type ofi
in the reverse thing,*(p1 + i)
, should be that type too (notice that*(p + i)
is equivalent top[i]
)