问题
According to C++ - should you size_t with a regular array?
§ 18.2 6 The type size_t is an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any object.
I don't understand why this guarantees a type size_t
to be big enough for an array index or big enough to represent the number of elements in an array.
For example:
int array[1000];
for (size_t i = 0; i < 1000; ++i) {
}
It seems unrelated to me why a "large enough number to contain the size in bytes of an object" == guarantees a type size_t
to be big enough for an array index".
回答1:
An array is an object. If size_t
can represent the size of the array in bytes, then it can also surely represent any index into it, since an individual element has at least one byte size.
An array with a larger size than that is simply not allowed by the language.
回答2:
It simply means, the largest array supported by the platform will be indexable with size_t
.
Consider:
int array[1000];
for (uint8_t i; i < 1000; ++i) {}
This is clearly wrong, uint8 does not have range to index that array. size_t
does, always, guaranteed by the standard.
As to why it is bytes, using sizeof array
gives byte size. There needs to be a type guaranteed to be able to represent the result.
I guess it would make more technical sense to use ptrdiff_t
to index arrays, because that is what array index kind of is: *(array+index)
. But that's not so common, I guess it looks uglier, is longer to type and may be more confusing.
Note that C++ standard does not make any similar guarantees about any other type. But this range issue is somewhat theoretical in most practical cases, as you can be sure that a 64 bit integer can also index anything that fits in the memory. It's more important for communicating intent.
来源:https://stackoverflow.com/questions/59728149/why-size-t-is-used-for-indexing-representing-size-of-an-array