Bring back foreach int indexes

Nick Treleaven nick at geany.org
Fri Dec 1 12:57:45 UTC 2023


On Thursday, 30 November 2023 at 21:28:51 UTC, Steven 
Schveighoffer wrote:
> 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`.

This code:

     foreach(ubyte idx, v; new int[270])
     {
         writeln(idx);
     }

Lowers to:

	{
		scope int[] __r72 = (new int[](270LU))[];
		ubyte __key71 = cast(ubyte)0u;
		for (; cast(int)__key71 < cast(int)cast(ubyte)__r72.length; 
cast(int)__key71 += 1)
		{
			int v = __r72[cast(ulong)__key71];
			ubyte idx = __key71;
			writeln(idx);
		}
	}

 From `dmd -vcg-ast`. So the array length is cast to ubyte, giving 
14.

> 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).

Well I get a deprecation message:

     Deprecation: foreach: loop index implicitly converted from 
`size_t` to `ubyte`

So I think it will become an error (at least in a future edition 
anyway).


More information about the Digitalmars-d mailing list