Avoid subtracting form .length

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Nov 9 04:02:46 UTC 2024


On Friday, November 8, 2024 4:27:40 PM MST Dom DiSc via Digitalmars-d-learn 
wrote:
> I _very_ often use this pattern:
>
> ```
> fun(ref int[] a)
> {
>     assert(a.length && a.length<=100);
>     int[100] b;
>     b[0 .. a.length-1] = a[];
>     b[a.length .. 100] = 5;
> }
> ```
>
> I consider this perfectly safe, but DScanner gives warnings for
> this, no matter if a check is present or not.
> What's the recommended fix for this? I have no idea what else to
> use.

Well, I don't know what it's warning about, but the code is wrong, because
the lengths of the slices don't match in

    b[0 .. a.length-1] = a[];

You'll get a RangeError being thrown when you run the code.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list