foreach on interval index by ref increment
Marco Leise
Marco.Leise at gmx.de
Sun Jan 22 01:55:08 PST 2012
Am 22.01.2012, 04:38 Uhr, schrieb bearophile <bearophileHUGS at lycos.com>:
> Regarding this code:
>
>
> import core.stdc.stdio;
> void main() {
> foreach (ref i; 0 .. 10) {
> printf("i = %d\n", i);
> i++;
> }
> }
>
>
> He says it "works as expected":
>
> i = 0
> i = 2
> i = 4
> i = 6
> i = 8
[...]
> Skipping to the next number to me looks like "i++" is doing something
> more like a pointer increment. It's ugly, and looks bug prone. foreach
> is not a light syntax sugar over a for loop, it's a bit different. I
> have discussed a similar topic some time ago.
Actually it is light syntax sugar over a for loop. The compiler sometimes
prints out the syntax tree. But I have to agree that this use of ref
doesn't look kosher. If I had my little way, I would adapt the ideas from
VB, where you would write the above loop as "for i=0 to 9 step 2". So in D:
foreach (i; 0 ... 9, +2)
also nice would be:
foreach (i; 9 ... 0)
The alternative:
foreach_reverse(i; 0 .. 10)
is really hard on the human brain :D
More information about the Digitalmars-d
mailing list