Possible 'pure' bug with int[] slice. Programming in D page 174

Quirin Schroll qs.il.paperinik at gmail.com
Wed Oct 15 12:16:10 UTC 2025


On Saturday, 4 October 2025 at 18:39:18 UTC, Alex Bryan wrote:
> On Saturday, 4 October 2025 at 12:40:43 UTC, Brother Bill wrote:
>> On Saturday, 4 October 2025 at 12:14:06 UTC, Dmitry Olshansky 
>> wrote:
>>> It’s weakly pure in that it could only mutate things that are 
>>> passed in. Strongly pure would require no mutable 
>>> pointers/slices/references.
>>> It may be misleading that it’s single keyword for both of 
>>> these. The good news is that strongly pure functions can call 
>>> weakly pure function and stay strongly pure.
>>
>> So if we don't want to allow mutating passing in parameters, 
>> add 'in' keyword to each parameter.  Then it should be 
>> strongly cure.  Is that correct?
>> ```
>> int[] inner(in int[] slice) pure
>> ```
>
> If you want to enforce (and also document) that an parameter is 
> never changed by the function, you should use `const`. If I'm 
> reading the spec correctly 
> (https://dlang.org/spec/function.html#in-params), `in` always 
> implies `const`, and with the -preview=in compiler switch, it 
> also implies `scope`

Correct, and additionally `in` parameters might be passed by 
reference at the discretion of the compiler, essentially 
depending on if it’s cheap to copy.

The TL;DR for `in` is: Only use it if you understand what it 
does. Generally speaking, use `const`. With DIP1000, preview-`in` 
on a `@system` function can give you nasty memory corruption bugs 
because the implied `scope` might make the compiler allocate 
something on the stack when it actually escapes. On a `@safe` 
function, the compiler will check that you don’t escape `scope` 
parameters, but on a `@system` function, the compiler simply 
trusts your promise.


More information about the Digitalmars-d-learn mailing list