foreach with assoc. array

DLearner bmqazwsx123 at gmail.com
Wed Mar 1 19:05:10 UTC 2023


Hi

Please consider (1):
```
void main() {
    import std.stdio;

    int wk_Idx;

    int[2] IntArr;

    IntArr[0] = 1;
    IntArr[1] = 2;

    for (wk_Idx = 0; wk_Idx <= 1; wk_Idx = wk_Idx + 1) {

       writeln("wk_Idx = ", wk_Idx, " IntArr = ", IntArr[wk_Idx]);
    }
}
```

Now consider (2), which is (1) via assoc. array:
```
void main() {
    import std.stdio;

    int wk_Idx;

    int[int] IntArr;

    IntArr[0] = 1;
    IntArr[1] = 2;

    for (wk_Idx = 0; wk_Idx <= 1; wk_Idx = wk_Idx + 1) {

       writeln("wk_Idx = ", wk_Idx, " IntArr = ", IntArr[wk_Idx]);
    }
}
```

And finally (3) which is (2) via a foreach:
```
void main() {
    import std.stdio;

    int wk_Idx;

    int[int] IntArr;

    IntArr[0] = 1;
    IntArr[1] = 2;

    foreach (wk_Idx; IntArr.keys) {

       writeln("wk_Idx = ", wk_Idx, " IntArr = ", IntArr[wk_Idx]);
    }
}
```

(1) & (2) compile and run with the expected results.
But (3) fails with:
```
Error: variable `wk_Idx` is shadowing variable `for3.main.wk_Idx`
```
Why is this usage wrong?



More information about the Digitalmars-d-learn mailing list