For subtraction of pointers i and j to elements of the same array object the note in [expr.add#5] reads:
[ Note: If the value i−j is not in the range of representable values of type
std::ptrdiff_t, the behavior is undefined. — end note ]
But given [support.types.layout#2], which states that (emphasis mine):
- The type
ptrdiff_tis an implementation-defined signed integer type that can hold the difference of two subscripts in an array object, as described in [expr.add].
Is it even possible for the result of i-j not to be in the range of representable values of ptrdiff_t?
PS: I apologize if my question is caused by my poor understanding of the English language.
EDIT: Related: Why is the maximum size of an array "too large"?
Yes, but it's unlikely.
In fact,
[support.types.layout]/2does not say much except the proper rules about pointers subtraction andptrdiff_tare defined in[expr.add]. So let us see this section.First of all, note that the case where
iandjare subscript indexes of different arrays is not considered. This allows to treati-jasP-Qwould be wherePis a pointer to the element of an array at subscriptiandQis a pointer to the element of the same array at subscriptj. In deed, subtracting two pointers to elements of different arrays is undefined behavior:As a conclusion, with the notation defined previously,
i-jandP-Qare defined to have the same value, with the latter being of typestd::ptrdiff_t. But nothing is said about the possibility for this type to hold such a value. This question can, however, be answered with the help ofstd::numeric_limits; especially, one can detect if an arraysome_arrayis too big forstd::ptrdiff_tto hold all index differences:Now, on usual target, this would usually not happen as
sizeof(std::ptrdiff_t) == sizeof(void*); which means an array would need to be stupidly big forptrdiff_tto overflow. But there is no guarantee of it.