Bug 251 – foreach does not allow updating inside with block

Status
RESOLVED
Resolution
INVALID
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D1 (retired)
Platform
x86
OS
Windows
Creation time
2006-07-13T18:38:00Z
Last change time
2014-02-15T13:22:19Z
Assigned to
bugzilla
Creator
ashleymedlock

Comments

Comment #0 by ashleymedlock — 2006-07-13T18:38:22Z
Array members cannot be updated inside a with block for either structs or classes. Sample code below: import std.stdio; struct Bar { float a= 1.0; } struct Foo { Bar[] arr; } void main( char[][] args ) { Foo foo ;//= new Foo(); foo.arr.length = 20; with(foo) { foreach( int n, Bar bar; arr ) bar.a = 100; } foreach( int n, Bar bar; foo.arr ) writefln("A=%s", bar.a ); }
Comment #1 by shro8822 — 2006-07-13T18:46:04Z
use inout with(foo) { foreach( int n, inout Bar bar; arr ) bar.a = 100; } haven't tested this but... INVALID I think
Comment #2 by andkhropov — 2006-07-14T09:40:17Z
BCS wrote: > I think that a basic foreach on an array requiters inout to change things. > > http://www.digitalmars.com/d/statement.html#foreach > > The opApply does requirer the inout (I ran into this a week or so back). This > seems like a problem to me. A non-inout version should be allowed so that > read only access can be granted. I agree too. But I would also like to have a warning or even completely disallow modifications of variables in foreach that are not declared as inout. The present situation is too error-prone: ----------------------------------------------------- foreach(i,k; a) // just forgot to type "inout". code does nothing k=i+1; ----------------------------------------------------- should be ----------------------------------------------------- foreach(i,k; a) k=i+1; // "warning: k is not inout" or "error: k is immutable". foreach(i,inout k; a) // ok k=i+1; ----------------------------------------------------- or maybe just a simple solution is to make them inout by default?
Comment #3 by bugzilla — 2008-06-24T21:53:08Z
This has nothing to do with it being in a with statement. At one point, the 'key' part of the foreach was set to 'final', meaning it could not be reassigned. This fell afoul of all the tail const problems, so it was abandoned. The current compiler is working as designed. The 'key' value is a mutable copy, unless it is declared as 'inout'.