Is D's pointer subtraction more permissive than C (and C++)?
Steven Schveighoffer
schveiguy at gmail.com
Sat Apr 2 17:58:52 UTC 2022
On 4/2/22 1:08 PM, Paul Backus wrote:
> On Saturday, 2 April 2022 at 02:20:34 UTC, Steven Schveighoffer wrote:
>> Right, but my larger point was, the *subtraction itself* is not harmful.
>>
>> There's two ways to look at this. First, if you subtract two pointers
>> that *aren't to the same block*, then the data is garbage. The other
>> way is that it is *undefined behavior*. I think *using* that
>> subtracted difference to e.g. index a pointer is what would be UB. But
>> the subtraction itself is ok.
>
> It's UB just to perform the subtraction:
>
>> [C11 § 6.5.6 ¶ 9][1] When two pointers are subtracted, both **shall**
>> point to elements of the same array object, or one past the last
>> element of the array object
>
>> [C11 § 4 ¶ 2][2] If a ''shall'' or ''shall not'' requirement that
>> appears outside of a constraint or runtime- constraint is violated,
>> the behavior is undefined.
>
> [1]: http://port70.net/~nsz/c/c11/n1570.html#6.5.6p9
> [2]: http://port70.net/~nsz/c/c11/n1570.html#4p2
Yep. That's a steep penalty.
It looks like C is trying to avoid having to specify how memory works
without actually specifying it (likely on purpose so it doesn't tie down
hardware developers to one memory model).
An interesting read I found on C and pointer comparisons here:
https://stefansf.de/post/pointers-are-more-abstract-than-you-might-expect/
-Steve
More information about the Digitalmars-d
mailing list