On my platform (and on most of them I think) std::size_t
and std::ptrdiff_t
have the same size and the same alignment. Is there any platform where that is not true? In short: is it required by the standard?
Size of 'size_t' and size of pointer are completely unrelated, so it is naturally to assume that such platforms exist in general case, regardless of whether they exist in reality.
size_t type is a base unsigned integer type of C/C++ language. It is the type of the result returned by sizeof operator. The type's size is chosen so that it can store the maximum size of a theoretically possible array of any type. On a 32-bit system size_t will take 32 bits, on a 64-bit one 64 bits.
ptrdiff_t is used for pointer arithmetic and array indexing, if negative values are possible. Programs that use other types, such as int, may fail on, e.g. 64-bit systems when the index exceeds INT_MAX or if it relies on 32-bit modular arithmetic.
size_t can store the maximum size of a theoretically possible object of any type (including array). size_t is commonly used for array indexing and loop counting.
In short: is it required by the standard?
No. The only requirement is from [support.types.layout]/2 and it is:
The type ptrdiff_t is an implementation-defined signed integer type that can hold the difference of two subscripts in an array object, as described in [expr.add].
There is paragraph 4
[ Note: It is recommended that implementations choose types for ptrdiff_t and size_t whose integer conversion ranks are no greater than that of signed long int unless a larger size is necessary to contain all the possible values. — end note ]
but notes are non-normative and it is only a recommendation, not a requirement.
std::size_t
is defined as
The type size_t is an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any object ([expr.sizeof]).
in paragraph 3 and it also has no requirement that they be the same.
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