Bug 22836 – [Reg 2.070/2.093] foreach using ubyte index over static array of length 256 or ushort index over static array of length 65536 does not execute the foreach body
Comment #0 by n8sh.secondary — 2022-03-02T15:55:48Z
Demonstration:
```
void main()
{
ubyte[256] array;
foreach (const ubyte i, ref a; array)
{
a = i;
}
assert(array[1] != 0); // Fails!
}
```
The above runs and the assertion passes in v2.069.2.
From v2.070.2 through v2.092.1 the above fails to compile with the error message "index type `const(ubyte)` cannot cover index range 0..256".
In v2.093.1 the above runs but the assertion fails.
Comment #1 by dkorpel — 2022-03-02T17:11:42Z
The compiler lowers it to
```
ubyte[] __r3 = array[];
ubyte __key2 = cast(ubyte)0u;
for (; cast(int)__key2 < cast(int)cast(ubyte)__r3.length; cast(int)__key2 += 1)
{
ref ubyte a = __r3[cast(ulong)__key2];
const const(ubyte) i = __key2;
a = i;
}
```
As you can see, the length is cast to a `ubyte`, so it overflows to a length of 0, which is why the loop body isn't entered.
Comment #2 by robert.schadek — 2024-12-13T19:21:16Z