| Thread overview | |||||
|---|---|---|---|---|---|
|
December 18, 2003 foreach gotchas | ||||
|---|---|---|---|---|
| ||||
With the for each val is always a copy, which means code like below is incorrect.
int [] array;
foreach (int i, int val; array)
{
val = 10;
}
I think in foreach val should be a reference.
What's worse, is if you iterate through an array of structs with foreach. In these cases there probably is a performance hit due to the copy.
-Anderson
| ||||
December 18, 2003 Re: foreach gotchas | ||||
|---|---|---|---|---|
| ||||
Posted in reply to J Anderson | You can do it with inout J Anderson <REMOVEanderson@badmama.com.au> wrote in news:brsd95$9iu$1@digitaldaemon.com: > With the for each val is always a copy, which means code like below is incorrect. > > int [] array; > > foreach (int i, int val; array) > { > val = 10; > } foreach (inout int i, int val; array) { val = 10; } > > I think in foreach val should be a reference. > > What's worse, is if you iterate through an array of structs with foreach. In these cases there probably is a performance hit due to the copy. > > -Anderson > > | |||
December 18, 2003 Re: foreach gotchas | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Patrick Down | Patrick Down wrote: >You can do it with inout > > Thanks. >J Anderson <REMOVEanderson@badmama.com.au> wrote in >news:brsd95$9iu$1@digitaldaemon.com: > > > >>With the for each val is always a copy, which means code like below is >>incorrect. >> >>int [] array; >> >>foreach (int i, int val; array) >>{ >> val = 10; >>} >> >> > >foreach (inout int i, int val; array) >{ > val = 10; >} > > > > > >>I think in foreach val should be a reference. >> >>What's worse, is if you iterate through an array of structs with foreach. In these cases there probably is a performance hit due to >>the copy. >> >>-Anderson >> >> >> >> > > > | |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply