Should (p - q) be disallowed in @safe code?
Timon Gehr
timon.gehr at gmx.ch
Fri Jan 2 22:54:50 UTC 2026
On 1/2/26 22:03, Walter Bright wrote:
> It seems we are in full agreement that p-q should be disallowed in @safe
> code, which is my proposal here.
> ...
I am happy with each of these two outcomes:
1. `p-q` is `@safe`, implementation-defined.
2. `p-q` can be UB, must be `@system`.
So, works for me.
> BTW, p-q is not a memory safety issue.
Any type of UB is a memory safety issue.
> At worst you get an integer result that is an unpredictable value.
No, _at worst_ you get e.g. the nuclear launch thing you mentioned (or
worse). Undefined semantics is starkly distinct from nondeterministic
semantics.
Any assumption that any type of UB is benign must rely on additional
information about specific backends. So what you claim may be true with
DMD, but that is about the extent of it.
> Yes, I am suggesting expanding the scope of @safe.
> ...
As long as `@safe` code consistently bans UB, the discussion of whether
banning UB from `@safe` code is an expansion of the scope of `@safe` is
mostly a philosophical one.
I am happy if `@safe` code disallows language constructs that can cause UB.
I think you are completely wrong to claim that this is an expansion of
the scope of `@safe`, but I will not lose any sleep over that part.
> `i<<j` can also result in nonsense if `j>=32`.
It is UB in C.
> But it is not unsafe.
UB implies unsafe. If it is not unsafe, it is not UB (e.g., in Java it
is safe and hence not UB).
> Given the pervasiveness of C, it would be insanity for a CPU to do
> anything other than seg fault or produce a random result.
I would expect a CPU to just do `i<<(j&31)`.
The C abstract machine is however not the CPU.
More information about the Digitalmars-d
mailing list