Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the unsigned counterpart of ptrdiff_t?

Tags:

c++

What is the unsigned counterpart of ptrdiff_t? And similarly - what is the signed counterpart of size_t?

What I'm trying to achieve is to have a unsigned type that I can use to store the positive values of ptrdiff_t variable without worrying about large values - this seems to be size_t.

Conversely - I would like to have a signed type that I can store the values of size_t, again without worrying about large values.

like image 772
Bartłomiej Siwek Avatar asked May 01 '12 13:05

Bartłomiej Siwek


People also ask

Is ptrdiff_ t signed?

ptrdiff_t is the signed integer type of the result of subtracting two pointers.

What is Ptrdiff_t?

ptrdiff_t type is a base signed integer type of C/C++ language. 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 ptrdiff_t will take 32 bits, on a 64-bit one 64 bits.

Is Size_t always unsigned?

Yes, size_t is guaranteed to be an unsigned type.

What is size_ t in C?

The datatype size_t is unsigned integral type. It represents the size of any object in bytes and returned by sizeof operator. It is used for array indexing and counting. It can never be negative. The return type of strcspn, strlen functions is size_t.


2 Answers

I don't think there is a formal unsigned counterpart to ptrdiff_t (no uptrdiff_t), but using size_t for it is pretty reasonable.

In POSIX, the signed counterpart to size_t is ssize_t. It is the type returned by functions such as read(), for example.

That suggests there will be few implementations where the underlying type of ssize_t and ptrdiff_t will be different.

like image 98
Jonathan Leffler Avatar answered Oct 25 '22 22:10

Jonathan Leffler


size_t is used to represent object sizes. It was widely believed that compiler writers will not create objects with negative sizes.

Note that with ptrdiff_t` you get the difference depending on how you are comparing, so a signed type makes sense (changing this to a unsigned type for reasonable values is trivial):

5.7 Additive operators

6 [...]As with any other arithmetic overflow, if the result does not fit in the space provided, the behavior is undefined.[...]

So, you may need to create a special type for 'very large values'.

like image 39
dirkgently Avatar answered Oct 26 '22 00:10

dirkgently