www.digitalmars.com Home | Search | C & C++ | D | DMDScript | News Groups | index | prev | next
Archives

D Programming
D
D.gnu
digitalmars.D
digitalmars.D.bugs
digitalmars.D.dtl
digitalmars.D.dwt
digitalmars.D.announce
digitalmars.D.learn
digitalmars.D.debugger

C/C++ Programming
c++
c++.announce
c++.atl
c++.beta
c++.chat
c++.command-line
c++.dos
c++.dos.16-bits
c++.dos.32-bits
c++.idde
c++.mfc
c++.rtl
c++.stl
c++.stl.hp
c++.stl.port
c++.stl.sgi
c++.stlsoft
c++.windows
c++.windows.16-bits
c++.windows.32-bits
c++.wxwindows

digitalmars.empire
digitalmars.DMDScript

D - foreach gotchas

↑ ↓ ← J Anderson <REMOVEanderson badmama.com.au> writes:
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
Dec 18 2003
↑ ↓ Patrick Down <pat codemoon.com> writes:
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
 
 

Dec 18 2003
↑ ↓ → J Anderson <REMOVEanderson badmama.com.au> writes:
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


    


Dec 18 2003