Bug 14984 – Make it illegal (or at least a warning) to modify the iteration variable in foreach
Status
RESOLVED
Resolution
WORKSFORME
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2015-08-30T12:26:35Z
Last change time
2022-10-10T09:29:37Z
Assigned to
No Owner
Creator
Marc Schütz
Comments
Comment #0 by schuetzm — 2015-08-30T12:26:35Z
Modifying the index variable in `foreach` is almost always wrong, for example:
https://github.com/D-Programming-Language/dmd/pull/4991
Thus, it should be deprecated and later forbidden. If someone really wants to, they can use a normal `for` loop.
Currently it's intentional. When you declare a index variable in foreach statement, it works like an auto variable scoped in the foreach body.
If you need non-mutable index variable, you can write code like:
foreach (const i, v; arr) { ... }
foreach (const i; 0..len) { ... }
Comment #3 by schuetzm — 2015-08-30T16:27:05Z
@Kenji Hara:
Yes, I know that. My point is that it's too easy to forget to add `const`.
Comment #4 by verylonglogin.reg — 2015-09-01T16:34:30Z
(In reply to Marc Schütz from comment #3)
> @Kenji Hara:
>
> Yes, I know that. My point is that it's too easy to forget to add `const`.
It's not a special `foreach` issue. It's a mistake to modify a variable in most cases as often it is just a constant view of data so if one doesn't follow "everything must be marked `const` except it is definitely mutable" it's his coding style problem. Unfortunately D doesn't solve this issue as it doesn't assume `const` by default. I hope the next D version will do it.
Comment #5 by razvan.nitu1305 — 2022-10-10T09:29:37Z
Right now, if we modify the element of a foreach range, there is no problem because we are operating on a copy of the original element. If we need to modify the actual element, then we need to add ref. That stands true for the iteration variable also. I don't see why we would deprecate any of this behavior because it offers maximum flexibility.