Regarding foreach loop index ranges
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Apr 21 06:34:52 PDT 2014
On Mon, 21 Apr 2014 07:49:03 -0400, bearophile <bearophileHUGS at lycos.com>
wrote:
> In this case I am not sure about bug reports, so I ask here.
>
> In this program the first loop doesn't compile, giving a nice error:
>
> test.d(3,5): Error: index type 'ubyte' cannot cover index range 0..300
>
> If you comment out the first loop, the second compiles and runs, but it
> seems to go in an infinite loop:
>
>
> void main() {
> int[300] data;
> foreach (ubyte i, x; data) {} // Error
> foreach (ubyte i, x; data[]) {} // compiles
> }
>
>
> 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.
A third option is allow the code to compile, but throw an assert in
non-release mode when the foreach statement is encountered "ubyte cannot
process all indexes of data."
This would be the least code-breaking option that saves a bug (you don't
know that the code can handle modulo indexes).
Then you could deprecate to disallowing ubyte indexes.
-Steve
More information about the Digitalmars-d-learn
mailing list