We know that, somehow, we use i
and j
variables in loops very commonly. If one need a double for
loop, it's very likely to use something like the following:
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
// do some stuff...
}
}
However, if I need a third for
loop in these loops, I don't have any naming convention for the third iterator. I, likely use the following variables: r
, k
, ii
, jj
etc...
Is there a naming convention for the third (and so on...) loop's iterator?
I actually almost never use i, I much prefer something like
cnt
, orindex
, orid
. For onecnt
is still short and quick to type. Also people will immediately know what it is when they look at your code, it's a counter and most importantly when you try to use Search for something like"i"
you will get a lot of junk you don't want to seeWhile if you
Ctrl+F
for index instead of i, or even more so for cnt you will only see what you expect to, so it's much more comfortable to navigate.For more complex loops though you should definitely type the full name of the variable though, you're just going to confuse yourself otherwise
There is no established convention for these things.
i
is fine for basic loops. For more complex loop or where the implementation isn't obvious at a glance, you should consider naming the iterators explicitly, e.g.surveyIndex
andquestionIndex
, rather thani
andj
.It's not uncommon to see nested loops in computer vision applications and, as other said, there is no convention, at least on the order of the letters, but generally people tend to use the letters
i,j,k,l,m,n,q,h...
This is for example a possible implementation of a 2-dimensional discrete convolution used for filtering images:
Here you can see another implementation in C++.
The most important thing for readability should be obvious names.
i and j aren't the most obvious, but may be ok for simple cases. Consider this (admittedly somewhat ill thought out) example;
vs
It's quite easy to see which makes more sense to read. But while we're at it, how about making it even more readable while eliminating your naming problem even more;
Maybe overkill/verbose for this simple loop, just wanted to make the point that there are more ways you can deal with the naming problem for nested loops than just finding unique names.