Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping: i vs loopCount [closed]

Is it better to use the variable 'i' or a meaningful name such as 'loopCount' or 'studentsCount' etc?

e.g.

for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 5; j++)
    {
        System.out.println(i + j);
    } // End of j loop
} // End of i loop

VS

for (int outerLoop = 0; outerLoop < 10; outerLoop++)
{
    for (int innerLoop = 0; innerLoop < 5; innerLoop++)
    {
        System.out.println(outerLoop + innerLoop);
    } // End of innerLoop
} // End of outerLoop

By better; the main considerations would be readability / conventions.

Related question Loop iterator naming convention

EDIT: I have tagged this a java, but answers for other languages are welcome.

like image 496
Möoz Avatar asked Feb 28 '14 02:02

Möoz


3 Answers

Firstly, using Integer here is very expensive because Integer is immutable. Thus each time you do an increment it unboxes the previous Integer, do an increment and creates another Integer to hold the new value. You need to use int.

Secondly, whether to have a readable name really up to the semantics of the int. If it's just a control variable over a pre-determined number of loops I think i is fine; but if it has specific meaning then you are free to give it a better meaningful name.

like image 200
Alex Suo Avatar answered Sep 24 '22 23:09

Alex Suo


Code is communication: what do you want the reader of this code (who might be you months or years from now) to think when he sees it? To me, using "i" and "j" in a loop says "do this thing 10 times; the variable is just a convention and means nothing", while using a more descriptive variable like "studentID" says "this number actually refers to something specific" I'd use the former if I want to de-emphasize the variable itself, and the latter if I want to highlight it.

like image 31
Lee Daniel Crocker Avatar answered Sep 25 '22 23:09

Lee Daniel Crocker


I have seen many loops that started out small and grew very large with other loops added inside and around them and it all became a confusing mess of i j k x y z. Name your references with the shortest name that expresses your intent, so another dev will know what you were going for.

like image 23
jeremyjjbrown Avatar answered Sep 22 '22 23:09

jeremyjjbrown