Avoid subtracting form .length

Salih Dincer salihdb at hotmail.com
Thu Nov 14 06:53:01 UTC 2024


On Friday, 8 November 2024 at 23:27:40 UTC, Dom DiSc wrote:
> I _very_ often use this pattern:
>
> ```d
> 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.

Why not use foreach in your code? Is there a specific reason for 
this? If I'm not mistaken, this is what you want to do:

```d
import std.array, std.range, std.stdio;

void fun(size_t size, int padding = 42)(ref int[] arr)
{
   assert(arr.length <= size, "Size Error!");
   int[size] sarr = padding;

   foreach(i, ref e; arr) sarr[i] = e;/*
   sarr[0 .. arr.length+ 1] = arr[];
   sarr[arr.length .. size] = padding;//*/

   sarr.writefln!"   %s";
}

void main()
{
   int[] arr = iota(5).array;
   arr.length.writeln(": ", arr);
   arr.fun!10;
} /*
   5: [0, 1, 2, 3, 4]
      [0, 1, 2, 3, 4, 42, 42, 42, 42, 42]
//*/
```

SDB79


More information about the Digitalmars-d-learn mailing list