Can sizeof(size_t)
be less than sizeof(int)
?
Do the C and/or C++ standards guarantee that using unsigned int
for array indexing is always safe?
Yes, sizeof(size_t)
can, in principle, be less than sizeof(int)
. I don't know of any implementations where this is true, and it's likely that there are none. I can imagine an implementation with 64-bit int
and 32-bit size_t
.
But indexing an array with unsigned int
is safe -- as long as the value of the index is within the bounds imposed by the length of the array. The argument to the []
operator is merely required to be an integer. It's not converted to size_t
. It's defined in terms of pointer arithmetic, in which the +
operator has one argument that's a pointer and another argument that is of any integer type.
If unsigned int
is wider than size_t
, then an unsigned int
index value that exceeds SIZE_MAX
will almost certainly cause problems because the array isn't that big. In C++14 and later, defining a type bigger than SIZE_MAX
bytes is explicitly prohibited (3.9.2 [compound.types] paragraph 2; section 6.9.2 in C++17). In earlier versions of C++, and in all versions of C, it isn't explicitly prohibited, but it's unlikely that any sane implementation would allow it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With