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

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Thu Jan 1 06:54:54 UTC 2026


On 01/01/2026 7:15 PM, Walter Bright wrote:
> Consider:
> ```d
> @safe
> size_t distance(int* p, int* q) => p - q;
> ```
> The difficulty here is when p and q may not be pointing into the same 
> memory object. If they're not, the result is nonsense:
> ```d
> int a;
> int b;
> size_t distance = &b - &a;
> ```
> The address relationship between `a` and `b` is implementation-defined, 
> and code like this would be almost certainly a bug.
> 
> Where this could be valid:
> ```d
> struct S
> {
>      int a,b;
> }
> S s;
> size_t distance = &s.b - &s.a;
> ```
> 
> So this would be valid, as the two pointers are known to point to the 
> same memory object.
> 
> A corollary to this would be disallowing < <= > >= comparisons between 
> pointers.
> 
> p-q is commonplace in C code, where one traverses a loop. But in D code 
> the preferred way would be to use arrays.
> 
> Thoughts?
> 
> P.S. I don't recall ever having a bug with misusing `p-q`. Has anyone?

Make it ptrdiff_t not size_t, and I'm happy.

The loops might go bad, but hey that is what static analyzers are for ;)



More information about the Digitalmars-d mailing list