Should (p - q) be disallowed in @safe code?
Walter Bright
newshound2 at digitalmars.com
Fri Jan 2 01:55:04 UTC 2026
On 1/1/2026 4:42 PM, Richard (Rikki) Andrew Cattermole wrote:
> That sounds a little like you're wanting to make safety designate which
> functions need static analysis.
Possibly, but not for the p-q case.
> However in this case it isn't required to make it disallow the operation:
>
> ``for (auto q = &array[0]; p - q; ++q)``
Right. Just disallow the p-q.
> If ``p - q`` is a /signed/ integer that cannot implicitly cast to unsigned, it
> will never iterate.
The loop works correctly whether the difference is signed or not.
> Both ``size_t`` and ``ptrdiff_t`` should be built in types that cannot
> implicitly cast off them. Making them aliases was a mistake.
Andrei proposed something like that years ago. Trying to write code with this
soup of same-but-different types turns out to be an awful soup, resulting in
lots of casting.
I've used a language that did not have implicit casting. The result was casts
everywhere, which winds up *increasing* the number of hidden bugs. C has a
well-designed implicit casting system (it isn't perfect) that is a lot more
flexible when one, for instance, wants to change the type of an integer.
> Note: @safe even with this upgrade does not track aliasing or not-aliasing. So
> if it is positive there is no way to know if it is the same object.
That's right. That's why p-q would be disallowed, whether or not it points to
the same memory object.
More information about the Digitalmars-d
mailing list