The size of the result is implementation-defined, and its type (a signed integer type) isptrdiff_t
defined in the<stddef.h>
header. If the result is not representable in an object of that type, the behavior is undefined. In other words, if the expressionsP
andQ
point to, respectively, the i-th and j-th elements of an array object, the expression(P) - (Q)
has the value i−j provided the value fits in an object of typeptrdiff_t
.
That means, while the type
size_t
is capable of expressing the size of any object, you cannot guarantee that the subtraction of two pointers inside your object will result in defined behavior. That is because ptrdiff_t
is signed (so it can give you the direction of the difference) and size_t
is unsigned. You can use the macros PTRDIFF_MAX
and SIZE_MAX
to determine if your subtraction is safe though.
No comments:
Post a Comment