9

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.

Faruk
  • 312
  • 3
  • 13
Bartłomiej Siwek
  • 1,447
  • 2
  • 17
  • 26

2 Answers2

8

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
4

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'.

Community
  • 1
  • 1
dirkgently
  • 108,024
  • 16
  • 131
  • 187