Is D's pointer subtraction more permissive than C (and C++)?

Paul Backus snarwin at gmail.com
Sat Apr 2 17:08:52 UTC 2022


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


More information about the Digitalmars-d mailing list