'Can sizeof(size_t) be less than sizeof(int)?
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?
Solution 1:[1]
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.
Solution 2:[2]
[C answer]
Can
sizeof(size_t)be less thansizeof(int)?
Yes. The size of size_t can be less, more or the same as int as their relative sizes/ranges are not specified in C - only their minimum _MAX values: 65535, 32767.
IMO, sizeof(size_t) < sizeof(int) is a unicorn. Theoretical, but not seen.
Code could use the following to detect such beasties.
#include <limits.h>
#include <stddef.h>
#if SIZE_MAX < UINT_MAX
#error Unexpected small size_t
#endif
Do the C and/or C++ standards guarantee that using
unsigned intfor array indexing is always safe?
In C, No.
Examples: A small array may only tolerate the indexes of [0 ... 2] - regardless of the type of the index - not the entire range of unsigned. A huge array may be index-able [0 ... UINT_MAX*42ull] and so an unsigned cannot represent all valid indexes.
A size_t is wide enough to index all arrays.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | chqrlie |
