Bring back foreach int indexes

Steven Schveighoffer schveiguy at gmail.com
Thu Mar 28 02:10:46 UTC 2024


On Sunday, 24 March 2024 at 16:33:06 UTC, Walter Bright wrote:

> Just use:
>
>     foreach (i; 0 .. array.length)
>
> and let the compiler take care of it for you.

The use case I have is you need to pass `i` to a function that 
takes an int. This is very common in C libraries (e.g. raylib).

Now, in this case, the solution is quite easy:

```d
foreach(i; 0 .. cast(int)array.length) // assumed
foreach(i; 0 .. array.length.to!int) // checked
```

But the case is *not* as easy with a foreach over an array with 
an index:

```d
foreach(int i, v; array)
```

In this case, without that mechanism, you have to cast i *every 
time it's used*. or have a goofy reassignment to another variable 
in each loop iteration.

This is one of those quality of life issues that would be nice to 
get back.

-Steve


More information about the Digitalmars-d mailing list