Am 22.01.2012, 04:38 Uhr, schrieb bearophile <[email protected]>:
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