Should (p - q) be disallowed in @safe code?
Paul Backus
snarwin at gmail.com
Thu Jan 1 17:56:43 UTC 2026
On Thursday, 1 January 2026 at 17:20:33 UTC, 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.
Pointer *subtraction* is allowed in @safe code because the result
is an integer, and all integers are [safe values][1].
For example, this compiles using the latest release of DMD:
```d
import std.stdio;
void main() @safe
{
int* p = new int, q = new int;
writeln(q - p);
}
```
[1]: https://dlang.org/spec/function.html#safe-values
More information about the Digitalmars-d
mailing list