foreach by value iteration

Jonathan M Davis jmdavisProg at gmx.com
Sun Feb 26 21:46:03 PST 2012


On Monday, February 27, 2012 05:51:37 Daniel Murphy wrote:
> On Sunday, 26 February 2012 at 10:25:31 UTC, Jonathan M Davis
> 
> wrote:
> > The index bit is highly debatable, as the discussion on that
> > shows
> > (personally, I tend to favor leaving it as-is, because it's
> > useful that way),
> > but regardless making either an rvalue wouldn't make any sense,
> > because they
> > have to be variables that you can operate on in the loop. Doing
> > anything else
> > would seriously break the semantics of foreach. The question is
> > simply whether
> > they should be actual copies so that you don't end up with them
> > altering
> > anything outside of the loop unless you mark them as ref or if
> > the type itself
> > is a reference type. The element is pretty much its own copy
> > regardless,
> > unless you mark it as ref, whereas the situation with the index
> > is more
> > complicated (as the discussion on that shows).
> > 
> > - Jonathan M Davis
> 
> Why does making either an rvalue not make any sense?
> 
> foreach(<modifiers> var; agg)
>     var = 7;
> 
> Then if var is not ref, the compiler marks it as an rvalue and
> gives an error if you try to modify or take the address of it.
> 
> It's pretty unlikely to happen, but it fixes the problem of
> accidentally modifying a foreach index or variable.  Just because
> it's in a variable doesn't mean the compiler can't treat it as an
> rvalue.

That would be _completely_ inconsistent with the rest of the language. 
Variables are _always_ lvalues. The closest that you can get to them being 
rvalues is if they're const or immutable, but even then, they're still 
lvalues, and you can take their address. It's just that the type system 
protects them from being altered.

But regardless, being unable to alter a foreach loop variable would be like 
making it so that you can no longer alter function parameters. Sure, it might 
fix some bugs, but it would be horribly restrictive a lot of the time.

- Jonathan M Davis


More information about the Digitalmars-d mailing list