Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does size_t have the same size and alignment as ptrdiff_t?

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?

like image 219
user7769147 Avatar asked May 21 '20 13:05

user7769147


People also ask

Is Size_t the same size as a pointer?

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.

What is the size of Size_t?

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.

What is Ptrdiff_t?

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.

What is the purpose of Size_t?

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.


1 Answers

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.

like image 187
NathanOliver Avatar answered Oct 13 '22 02:10

NathanOliver