Jump to content

Talk:Loop counter

Page contents not supported in other languages.
From Wikipedia, the free encyclopedia

Reuse of loop counter

[edit]

I was wondering if someone can safely reuse a loop counter in another loop further down in the same program. Example (bash):

echo "first loop:"
for i in ${Array[@]}
 do
  echo $i
 done

echo "second loop:"
for i in ${Array[@]}
 do
  echo $i
 done

I am aware that variable reusing is something someone should avoid. But how about this special case of loop counter variables? Are those used only in the loop and then the next loop can safely reuse them again, so that someone can stick e.g. to "i", "j", "k", etc. throughout his program, or could this bring someone into trouble, as regular variable reusing can, so that he should think of new loop counter variables for each loop, e.g. i1, i2, i3, j1, j2, k1, k2, etc.? It would be great if someone could add a paragraph to the article giving information about the usage of loop counter variables and their ability / disability to be reused in one program and - in the case that their reusing should be perfectly safe - point out that this is a big difference compared to "regular" variables (i.e. non-loop-counter-variables) --62.169.207.133 (talk) 17:00, 9 June 2015 (UTC)[reply]