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

Timon Gehr timon.gehr at gmx.ch
Thu Jan 1 20:57:05 UTC 2026


On 1/1/26 18:20, Walter Bright wrote:
> On 1/1/2026 7:16 AM, claptrap wrote:
>> I use this all the time to iterate multiple arrays in lockstep.
>>
>> size_t offset = q-p;
>>
>> you access q with "p[offset]", and you just iterate p
>>
>> I tried to avoid using it but it is just faster sometimes,
> 
> @safe code doesn't allow pointer arithmetic, and so such code would have 
> to be marked @trusted anyway.

It's one question whether you have to mark it `@trusted` for it to type 
check, it's another question whether you are allowed to mark it 
`@trusted` (i.e., whether it is actually memory safe).

In C, I think adding an integer to a pointer aiming to get a result that 
points to a different memory object entirely would just be UB.

I.e., there is some potential for `q+(p-q)` to do something other than 
give you `p` unless glue code and backends are careful to handle it as 
intended.

As far as I can tell, such nuances are not documented in the D spec and 
so it would be defensible for GDC and LDC to assume it's just supposed 
to mimic C behavior. Whether the backends actually do end up breaking 
assumptions like they would be allowed to is still another question.


More information about the Digitalmars-d mailing list