If you have the followin开发者_如何学Pythong code where p is a pointer:
p = p + strlen(p) + size_t(1);
Since strlen()
and size_t
are both size_t
, should I cast the code to ptrdiff_t
?
p = p + (ptrdiff_t)(strlen(p) + size_t(1));
If so why?
Thanks, Greg
std::ptrdiff_t is signed. std::size_t is unsigned. Casting strlen(p)
to ptrdiff_t
would make sense if p
could have a negative length, which is not possible.
However, that cast could overflow the resulting signed value if p
is large enough (for instance, larger than 2,147,483,647 bytes on most 32-bit platforms). So it could introduce an error in your pointer arithmetic.
Best to stick with size_t
here.
There's no need to cast to ptrdiff_t
. Pointer arithmetic is well-defined for all integral types, including size_t
, and if size_t
wasn't big enough to hold the value, the cast to ptrdiff_t
comes too late anyway.
Here is the relevant language from the Standard (C++0x FCD, section [expr.add]
):
When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. In other words, if the expression P points to the i -th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n ) point to, respectively, the i + n -th and i − n -th elements of the array object, provided they exist. Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.
精彩评论