Should (p - q) be disallowed in @safe code?

Walter Bright newshound2 at digitalmars.com
Sat Jan 3 19:28:49 UTC 2026


On 1/2/2026 3:17 PM, Timon Gehr wrote:
> One memory-safe alternative semantics to UB would be: if arguments point to 
> different memory objects, you may get any result value. This can still be 
> implemented by your "practical effect" above, but now it's memory safe (in 
> isolation).

I've said that it was memory safe all along. I've said this proposal is 
extending @safe beyond memory safety to include bug detection of other things 
like p-q.

> You could have an even stronger semantics that also guarantees things like `p is 
> p+(q-p)`.

I don't see any particular use for recognizing that. There are an infinite 
number of patterns that can be recognized, it's only useful to recognize ones 
that occur commonly.

BTW, the optimizer does recognize i+(j-i) as being just j, and it will do it for 
pointers to 1 byte objects. For pointers to int, the intermediate code looks 
like p+((q-p)/4)*4 which is not recognized.

>> The only thing D can do is in @safe code simply disallow p-q, as there are 
>> good alternatives to do the equivalent thing.
> 
> It's absolutely not the only possible thing. It is just one way (the C way) to 
> deal with the issue.

Please explain the other ways.


More information about the Digitalmars-d mailing list