Friday, July 29, 2011

C Gotcha Of The Day: ptrdiff_t

Excerpt from C99 Draft (AFAIK this has not changed):

The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_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 expressions P and Q 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 type ptrdiff_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