Foreach loops on static arrays error message

Guillaume Chatelet via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 6 01:26:42 PDT 2017


I stumbled upon https://issues.dlang.org/show_bug.cgi?id=12685

In essence:

> ubyte[256] data;
> foreach (ubyte i, x; data) {}
> 
> Error: index type 'ubyte' cannot cover index range 0..256

`ubyte` can clearly hold a value from 0 to 255 so it should be 
ok. No need for 256 ?!

So I decided to fix it https://github.com/dlang/dmd/pull/6973

Unfortunately when you think about how foreach is lowered it 
makes sense - but the error message is misleading.

The previous code is lowered to:

> ubyte[256] data;
> for (ubyte i = 0 ; i < 256 ; ++i) {
>   ubyte x = data[i]
> }

`i < 256` is always true, this would loop forever.

Questions:
- What would be a better error message?
- How about a different lowering in this case?

 From the programmer's point of view the original code makes sense.
A correct lowering would be:

> ubyte[256] data;
> for(ubyte i = 0;;++i) {
>    ubyte x = data[i];
>    ...
>    if(i==255) break;
> }


More information about the Digitalmars-d mailing list