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

Timon Gehr timon.gehr at gmx.ch
Fri Jan 2 23:17:45 UTC 2026


On 1/2/26 20:51, Walter Bright wrote:
> ...
> 
> In general, it is not possible for the compiler to ensure two pointers 
> point to the same object without expensive instrumentation added to the 
> code. The practical effect is to assume they do, subtract the values, 
> and divide by the size of the type.
> ...

This is what people intuitively assume will happen, but UB is not this. 
UB is notoriously prone to confusing programmers as well as compiler 
writers.

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).

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

The source and target semantics are the only things the optimizer really 
tends to care about.

> 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.


More information about the Digitalmars-d mailing list