digitalmars.D.learn - foreach with assoc. array
- DLearner (46/46) Mar 01 2023 Hi
- Paul Backus (4/11) Mar 01 2023 With `foreach`, you can't reuse an existing variable as the loop
- Salih Dincer (15/20) Mar 02 2023 Or use the `each` template which is almost the same as `foreach`
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?
Mar 01 2023
On Wednesday, 1 March 2023 at 19:05:10 UTC, DLearner wrote:(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?With `foreach`, you can't reuse an existing variable as the loop variable. It always declares a new one. If you want to reuse an existing variable for your loop, you have to use `for`.
Mar 01 2023
On Wednesday, 1 March 2023 at 19:05:10 UTC, DLearner wrote:``` Error: variable `wk_Idx` is shadowing variable `for3.main.wk_Idx` ``` Why is this usage wrong?Or use the `each` template which is almost the same as `foreach` to avoid the shadowing variable issue. ```d import std.algorithm, std.range, std.stdio; enum len = 10; void main() { int[len] IntArr, i, n; len.iota.each!((i, n) => IntArr[i] = n); IntArr.writeln; // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] assert(IntArr == len.iota.array); } ``` SDB 79
Mar 02 2023