suggested change to foreach index
Deewiant
deewiant.doesnotlike.spam at gmail.com
Thu Jun 8 01:51:55 PDT 2006
Sean Kelly wrote:
> What's weird to me is if I do this:
>
> void main()
> {
> int i;
> char[] arr = "abc def";
>
> foreach( i, c; arr )
> {
> printf( "%i\n", i );
> if(' ' == c)
> break;
> }
> printf( "\n%i\n", i );
> }
>
> Then the output is:
>
> 0
> 1
> 2
> 3
>
> 0
>
> So the code compiles without a type for i in the foreach, but rather
> than use the instance of i in the surrounding scope a local value is
> used instead. The spec isn't clear on what should happen here, but I
> would have guessed that the final value displayed would be 3, not 0.
>
>
> Sean
It creates a new scope, just like for loops:
int i = 5;
for (int i = 0; i < 3; ++i)
writefln(i); // 0 to 2
writefln(i); // 5
I don't know about the spec's opinion, but this is how it has always worked,
both with for and foreach, and I have a lot of code that relies on this behaviour.
The "inout" suggested elsewhere in the thread by Regan Heath seems like a good
solution to me.
More information about the Digitalmars-d
mailing list