C ++ size_t or ptrdiff_t

If you have the following code, where p is a pointer:

p = p + strlen(p) + size_t(1); 

Since strlen() and size_t both size_t , should I pass the ptrdiff_t code?

 p = p + (ptrdiff_t)(strlen(p) + size_t(1)); 

If so, why?

Thanks Greg

+8
c ++
source share
2 answers

std :: ptrdiff_t . std :: size_t is unsigned. Listing strlen(p) to ptrdiff_t makes sense if p can have a negative length, which is not possible.

However, this tide can overflow the resulting signed value if p is large enough (for example, on most 32-bit platforms, more than 2,147,483,647 bytes). Thus, this can lead to an error in your pointer arithmetic.

It is best to stick with size_t here.

+14
source share

No need to throw in ptrdiff_t . Pointer arithmetic is well defined for all integral types, including size_t , and if size_t not large enough to hold the value, casting to ptrdiff_t happens anyway.

Here is the corresponding language from the standard (C ++ 0x FCD, section [expr.add] ):

When an expression having an integral of type is added or subtracted from the pointer, the result has the form of a pointer operand. If the operand pointer points to an array element, the array is massive enough, the result indicates the offset of the element from the original element, so that the difference between the indices obtained and the original array elements are equal to the integral expression. In other words, if the expression P points to the ith element of the array, the expressions (P) + N (equivalently, N + (P)) and (P) -N (where N has the value n) indicate, respectively, i + n -th and inth elements are an array object, if they exist. Moreover, if the expression P points to the last element of the array object, the expression (P) +1 indicates one after the last element of the array of the object, and if the expression Q points one after the last element of the array object, the expression (Q) -1 indicates the last element of the object array. If both the pointer operand and the result point to elements of the same array object or one last element of the array object, the evaluation should not overflow; otherwise, the behavior is undefined.

+2
source share

Source: https://habr.com/ru/post/649906/


All Articles