On Fri, 2 Nov 2012, Logan Kelly wrote:
The following two code fragments seem at first glance to be the same
loop i = 1..3
and
loop for (i=1; i<=3; 1+=1)
Could someone comment on the best practice of when to use
what loop type?
I would say, go with simplicity where possible. I would always
use the first of the two formulations above. However, I might
use the second form if I wanted to do something more
complicated such as
for (x=20; x>0; x-=0.5)
Also, one could loop over a list using an index loop or a
foreach loop. Which is best practice when? Are there any
general guidelines?
You need a foreach loop to access list members in a function,
where the list was provided as an argument. It would also be
"natural" to use a foreach loop if you want to access the
names of the list members (via $i).
There's some redundancy in the loop variants offered by hansl
(as, in fact, in most programming languages, including C).
There are really no hard and fast guidelines, it's just a
matter of figuring which seems simplest for the task in hand.
Allin Cottrell