I've always wondered: isn't ptrdiff_t
supposed to be able to hold the difference of any two pointers by definition? How come it fails when the two pointers are too far? (I'm not pointing at any particular language... I'm referring to all languages which have this type.)
(e.g. subtract the pointer with address 1
from the byte pointer with address 0xFFFFFFFF
when you have 32-bit pointers, and it overflows the sign bit...)
No, it is not.
$5.7 [expr.add] (from n3225 - C++0x FCD)
When two pointers to elements of the same array object are subtracted, the result is the difference of the subscripts of the two array elements. The type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined asstd::ptrdiff_t
in the<cstddef>
header (18.2). As with any other arithmetic overflow, if the result does not fit in the space provided, the behavior is undefined. In other words, if the expressionsP
andQ
point to, respectively, thei
-th andj
-th elements of an array object, the expression(P)-(Q)
has the valuei − j
provided the value fits in an object of typestd::ptrdiff_t
. Moreover, if the expressionP
points either to an element of an array object or one past the last element of an array object, and the expressionQ
points to the last element of the same array object, the expression((Q)+1)-(P)
has the same value as((Q)-(P))+1
and as-((P)-((Q)+1))
, and has the value zero if the expressionP
points one past the last element of the array object, even though the expression(Q)+1
does not point to an element of the array object. Unless both pointers point to elements of the same array object, or one past the last element of the array object, the behavior is undefined.
Note the number of times undefined
appears in the paragraph. Also note that you can only subtract pointers if they point within the same object.
No, because there is no such thing as the difference between "any two pointers". You can only subtract pointers to elements of the same array (or the pointer to the location just past the end of an array).
To add a more explicit standard quote, ISO 9899:1999 §J.2/1
states:
The behavior is undefined in the following circumstances:
[...]
-- The result of subtracting two pointers is not representable in an object of type ptrdiff_t (6.5.6).
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