Question:

Naming loop indexes in programming?

by  |  earlier

0 LIKES UnLike

Hi,

when you have loops throughout a program, do people usually name the first index i, then the next j, etc, when the loops are in the same scope level? How about when the loops are in different scope levels--do you start over at i each time, so you have multiple loop indexes named i, j, etc., but they are in different scopes? Or do you never want to have loop indexes with the same names in a program, so you increment the loop name each time, so you never have two loop indexes with the same name such as two different i's in a program? Thanks!

 Tags:

   Report

4 ANSWERS


  1. Personally, I avoid using variables with names like i, j, or k.  Using a more descriptive name like someIndex helps code readability.  It also helps me avoid creating bugs, such as using j where k should be.  Errors like that become obvious if you use variables like some[someIndex].

    If you do insist on using such arbitrary variables, I would start over.  

    Either way, define the variable at the smallest scope possible.  Don't re-use the variables outside the scope of the loop.  That is a sure way to get into trouble.


  2. Like warsql I would never use i, j or k.  All my variables (including loops counters) are called something that describes what they are.  The idea is to improve the readabilty of the code.

    For a loop counter I commonly use the name of the thing it's looping through or over, the reason why it's looping. For example, if I'm rendering in 3 passes the counter would be numPass, if I'm looping over a list of names it would be numName.

    I reuse the names in the same scope or any other scope, but never inside a scope.  The most important thing is readability, loop counters should only be local scope anyway.

    I tend to use 'num' rather than 'index'.  I use 'idx' for the names of variables that are used as indices, rather than counters, a very important distinction.

  3. Name them whatever you want. It does not matter.

  4. Usually u'd call ur the outer  loop index variable 'i' then the next inner 'j' then 'k' (but don't go too beyond three levels of loops ). If you declare the loop variables INSIDE the for/while strcure then NO problem if u use the same names latter in the same source file .Example in C/C++ language :

    for( int i = 0 ; i <100 ; i++)  // here the var i is declared of type integer IN                the loop

    But if declare the variable OUTSIDE the loop structure then this is an error , as the loop variable is NOT local to the loop itself anymore  

Question Stats

Latest activity: earlier.
This question has 4 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions