operator [] by pointers can be any integral expression
To be general, ptrdiff_t technically what you want if the intention is for data and data + i be any two arbitrary pointers in any other and arbitrary blocks of memory, since ptrdiff_t defined as a signed type to store the difference between two pointers ( however, it is not guaranteed to not overflow: ptrdiff_t on machines with 32-bit pointers is usually 32-bit and not the next signed integral size above)
std::vector<T> uses size_t , size_t , since std::vector has an additional restriction indicating that the pointer points to the beginning of the block, and indexing is allowed only inside the selected block, which cannot be larger than size_t by definition, and negative signs are not allowed. size_t may be less than ptrdiff_t or uintptr_t (unsigned integral type that may contain a pointer), for example, on segmented architectures in which memory allocations are limited to one segment, but pointers are not.
Now, if the intention is that data and data + i are part of the same memory block, but not necessarily the same as data + i >= data , then I donโt think there is an exact type of natural data (i.e. e. a signed analogue of size_t ... Maybe I'm wrong) in standard C ++ ( ssize_t is a POSIX extension), but you can go with ptrdiff_t , as it is guaranteed to be as small as possible.
There is no guarantee that sizeof(long) or sizeof(int) has anything to do with sizeof(ptrdiff_t) or sizeof(size_t) ... provided that this can lead to unpleasant errors.
EDIT . Technically, there is no portable way to get data and i so that data and data + i are valid pointers and point to different objects in different allocation blocks, since the standard only ensures that pointer arithmetic is well defined in the selected block, so if you rely on it , your program is not portable anyway. (Not that this does not work, in most cases ...)
source share