Let’s say you have a piece of code where you have a for-loop, followed by another for-loop and so on… now, which one is preferable
-
Give every counter variable the same name:
for (int i = 0; i < someBound; i++) { doSomething(); } for (int i = 0; i < anotherBound; i++) { doSomethingElse(); } -
Give them different names:
for (int i = 0; i < someBound; i++) { doSomething(); } for (int j = 0; j < anotherBound; j++) { doSomethingElse(); }
I think the second one would be somewhat more readable, on the other hand I’d use j,k and so on to name inner loops… what do you think?
I reuse the variable name in this case. The reason being that
iis sort of international programmerese for “loop control variable whose name isn’t really important”.jis a bit less clear on that score, and once you have to start usingkand beyond it gets kind of obscure.One thing I should add is that when you use nested loops, you do have to go to
j,k, and beyond. Of course if you have more than three nested loops, I’d highly suggest a bit of refactoring.