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

Walter Bright newshound2 at digitalmars.com
Thu Jan 1 06:15:09 UTC 2026


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?


More information about the Digitalmars-d mailing list