Regarding foreach loop index ranges

bearophile via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Apr 21 05:03:20 PDT 2014


> For the second loop one possible alternative behavour is to 
> refuse a ubyte index and accept only a size_t index if it loops 
> on a dynamic array.
> Another alternative is: the i variable can go from 0 to 255, 
> then go up to the modulus of the remaining indexes, and then 
> stop.

In this program the assignment to x1 is accepted, but the 
assignments to x2 and x3 are refused:

void main() {
     int[200] data1;
     ubyte x1 = data1.length;
     int[300] data2;
     ubyte x2 = data2.length;
     auto data3 = new int[300];
     ubyte x3 = data3.length;
}

So I think the simplest solution is to refuse this code, because 
like the assignment of x3 it tries to assign a size_t value 
unknown at compile time to an ubyte:

void main() {
     int[300] data;
     foreach (ubyte i, x; data[]) {}
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list