Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 999
NoSkill Avatar asked Dec 13 '22 09:12

NoSkill


1 Answers

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.

like image 177
Keith Thompson Avatar answered Dec 15 '22 23:12

Keith Thompson