Should (p - q) be disallowed in @safe code?
Walter Bright
newshound2 at digitalmars.com
Fri Jan 2 19:51:55 UTC 2026
On 1/1/2026 6:11 PM, Timon Gehr wrote:
> Let's say the frontend now treats `p-q` as `@system`, and there is not even any
> documentation of what its semantics is supposed to be.
The current documentation says:
"If both operands are pointers, and the operator is -, the pointers are
subtracted and the result is divided by the size of the type pointed to by the
operands. In this calculation the assumed size of void is one byte. It is an
error if the pointers point to different types. The type of the result is
ptrdiff_t."
https://dlang.org/spec/expression.html#pointer_arithmetic
C11 says:
"When two pointers are subtracted, both shall point to elements of the same
array object, or one past the last element of the array object; the result is
the difference of the subscripts of the two array elements."
and:
"The behavior is undefined in the following circumstances: A ‘‘shall’’ or
‘‘shall not’’ requirement that appears outside of a constraint is violated
(clause 4)."
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.
The only thing D can do is in @safe code simply disallow p-q, as there are good
alternatives to do the equivalent thing.
More information about the Digitalmars-d
mailing list