Bring back foreach int indexes
Steven Schveighoffer
schveiguy at gmail.com
Thu Nov 30 21:28:51 UTC 2023
On Thursday, 30 November 2023 at 18:26:55 UTC, Johan wrote:
>
> - What about the other integer types? (uint, short, byte,
> char?)
Yeah, you can use those too. I think the right answer is to
ensure the length of the array being iterated can't exceed the
value range of the type using an assert.
And oh god, I know we have to do `char` because "it's an integer
too!". `bool` is also, you could do `foreach(bool idx, v; arr)`
> - What if `arr.length >= int.max` ? Does the loop become
> infinite, or does the loop counter stay `size_t` (not
> accessible by user) and it is cast to `int` (`idx`) upon every
> iteration ?
I actually tested this (with `ubyte`, not `int`), and what
happens is interesting. You only get `length % T.max` (or
something like that) elements.
For instance I did:
```d
foreach(ubyte idx, v; iota(270).array)
{
writeln(idx);
}
```
and it printed 0 to 13, and was done.
So clearly it uses `ubyte` as the index for iteration, and also
somehow converts the length to `ubyte` instead of the other way
around.
But it doesn't use it exactly, because modifying `idx` doesn't
change the loop. So I don't see why it uses `ubyte` for the
actual index instead of `size_t`.
Honestly, maybe the easiest fix here is just to fix the actual
lowering to be more sensical (I would have expected 270
iterations with repeated indexes 0 to 13 after going through 255).
-Steve
More information about the Digitalmars-d
mailing list