Why is ptrdiff_t signed?

382 Views Asked by At

If ptrdiff_t were unsigned, it would be able to refer to twice as many elements. On my machine PTRDIFF_MAX is expanded to 9223372036854775807i64, whereas ULLONG_MAX is 18446744073709551615Ui64.

I know that these values are huge themselves, but if

The type (ptrdiff_t)'s size is chosen so that it can store the maximum size of a theoretically possible array of any type.

ref

then doesn't making it unsigned make more sense?

1

There are 1 best solutions below

0
On BEST ANSWER

If ptrdiff_t were unsigned, it would be able to refer to twice as many elements.

That is not correct. Making a type unsigned does not magically increase the amount of information it can hold. Signed and unsigned integers of the same size have exactly the same number of different states. In the signed version, half the states represent negative numbers. And you do need negative numbers to handle the result of subtracting a pointer with a higher address value from one with a lower address value. For instance:

int arr[42];
int* p1 = arr;
int* p2 = arr + 42;
auto diff = p1 - p2; // what should the result be?