What is an ideal variable naming convention for loop variables?
Solution 1
I always use a meaningful name unless it's a single-level loop and the variable has no meaning other than "the number of times I've been through this loop", in which case I use i
.
When using meaningful names:
- the code is more understandable to colleagues reading your code,
- it's easier to find bugs in the loop logic, and
- text searches for the variable name to return relevant pieces of code operating on the same data are more reliable.
Example - spot the bug
It can be tricky to find the bug in this nested loop using single letters:
int values[MAX_ROWS][MAX_COLS];
int sum_of_all_values()
{
int i, j, total;
total = 0;
for (i = 0; i < MAX_COLS; i++)
for (j = 0; j < MAX_ROWS; j++)
total += values[i][j];
return total;
}
whereas it is easier when using meaningful names:
int values[MAX_ROWS][MAX_COLS];
int sum_of_all_values()
{
int row_num, col_num, total;
total = 0;
for (row_num = 0; row_num < MAX_COLS; row_num++)
for (col_num = 0; col_num < MAX_ROWS; col_num++)
total += values[row_num][col_num];
return total;
}
Why row_num
? - rejected alternatives
In response to some other answers and comments, these are some alternative suggestions to using row_num
and col_num
and why I choose not to use them:
-
r
andc
: This is slightly better thani
andj
. I would only consider using them if my organisation's standard were for single-letter variables to be integers, and also always to be the first letter of the equivalent descriptive name. The system would fall down if I had two variables in the function whose name began with "r", and readability would suffer even if other objects beginning with "r" appeared anywhere in the code. -
rr
andcc
: This looks weird to me, but I'm not used to a double-letter loop variable style. If it were the standard in my organisation then I imagine it would be slightly better thanr
andc
. -
row
andcol
: At first glance this seems more succinct thanrow_num
andcol_num
, and just as descriptive. However, I would expect bare nouns like "row" and "column" to refer to structures, objects or pointers to these. Ifrow
could mean either the row structure itself, or a row number, then confusion will result. -
iRow
andiCol
: This conveys extra information, sincei
can mean it's a loop counter whileRow
andCol
tell you what it's counting. However, I prefer to be able to read the code almost in English:-
row_num < MAX_COLS
reads as "the row number is less than the maximum (number of) columns"; -
iRow < MAX_COLS
at best reads as "the integer loop counter for the row is less than the maximum (number of) columns". - It may be a personal thing but I prefer the first reading.
-
An alternative to row_num
I would accept is row_idx
: the word "index" uniquely refers to an array position, unless the application's domain is in database engine design, financial markets or similar.
My example above is as small as I could make it, and as such some people might not see the point in naming the variables descriptively since they can hold the whole function in their head in one go. In real code, however, the functions would be larger, and the logic more complex, so decent names become more important to aid readability and to avoid bugs.
In summary, my aim with all variable naming (not just loops) is to be completely unambiguous. If anybody reads any portion of my code and can't work out what a variable is for immediately, then I have failed.
Solution 2
1) For normal old style small loops - i, j, k - If you need more than 3 level nested loops, this means that either the algorithm is very specific and complex, or you should consider refactoring the code.
Java Example:
for(int i = 0; i < ElementsList.size(); i++) {
Element element = ElementsList.get(i);
someProcessing(element);
....
}
2) For the new style java loops like for(Element element: ElementsList)
it is better to use normal meanigful name
Java Example:
for(Element element: ElementsList) {
someProcessing(element);
....
}
3) If it is possible with the language you use, convert the loop to use iterator
Java Iterator Example: click here
Solution 3
My experience is that most people use single letters, e.g.:
i
,
j
,
k
,
...
or
x
,
y
,
or
r
,
c
(for row/column)
or
w
,
h
(for width/height)
, etc.
But I learned a great alternative a long time ago, and have used it ever since: double letter variables.
// recommended style ● // "typical" single-letter style
●
for (ii=0; ii<10; ++ii) { ● for (i=0; i<10; ++i) {
for (jj=0; jj<10; ++jj) { ● for (j=0; j<10; ++j) {
mm[ii][jj] = ii * jj; ● m[i][j] = i * j;
} ● }
} ● }
In case the benefit isn't immediately obvious: searching through code for any single letter will find many things that aren't what you're looking for. The letter i
occurs quite often in code where it isn't the variable you're looking for.
Solution 4
Examples: . . . In Java
Non-Iterative Loops:
Non-Nested Loops: . . . The Index is a value.
. . . using
i
, as you would in Algebra, is the most common practise . . .
for (int i = 0; i < LOOP_LENGTH; i++) {
// LOOP_BODY
}
Nested Loops: . . . Differentiating Indices lends to comprehension.
. . . using a descriptive suffix . . .
for (int iRow = 0; iRow < ROWS; iRow++) {
for (int iColumn = 0; iColumn < COLUMNS; iColumn++) {
// LOOP_BODY
}
}
foreach
Loops: . . . An Object
needs a name.
. . . using a descriptive name . . .
for (Object something : somethings) {
// LOOP_BODY
}
Iterative Loops:
for
Loops: . . . Iterators reference Objects. An Iterator it is neither; an Index, nor an Indice.
. . .
iter
abreviates an Iterators purpose . . .
for (Iterator iter = collection.iterator(); iter.hasNext(); /* N/A */) {
Object object = iter.next();
// LOOP_BODY
}
while
Loops: . . . Limit the scope of the Iterator.
. . . commenting on the loops purpose . . .
/* LOOP_DESCRIPTION */ {
Iterator iter = collection.iterator();
while (iter.hasNext()) {
// LOOP_BODY
}
}
This last example reads badly without comments, thereby encouraging them. It's verbose perhaps, but useful in scope limiting loops in C.
Solution 5
Always try to name the variable something meaningful and in context.
If you cannot decide, then use "index", if only so that someone else (maybe you!) can more easily click on it for refactoring later.
Paul Stephenson See this answer for an example.
just mike
geek developer maker not a DBA tags created: consistency discipline member since 2008-09-16 http://j.mp/SOjustmike http://stackoverflow.com/privileges
Updated on July 09, 2022Comments
-
just mike almost 2 years
If you are writing a simple little loop, what should you name the counter?
Provide example loops!
-
Jon Limjap over 15 yearsThey look quite unreadable to me, especially parallel-line letters (e.g., ii, ll, jj, etc.)
-
Jon Limjap over 15 yearsBesides, why do you need to search for loop variables when they shouldn't reside anywhere beyond the loop? Not unless you have tons of code in between -- which isn't a good idea.
-
Magnar over 15 yearsIf you need to search for your iteration-variables, then it's refactoring-time!
-
Jon Limjap over 15 yearsWhich is ironic Magnar, because he did say "simple little loop". LOL
-
Saurabh over 15 yearsSwitch to an editor that lets you include word boundaries in search patterns, e.g. '\<i\>' or has a "whole word only" checkbox.
-
Bill Michell over 15 yearsIf your variables have meaning outside the loop, then don't call them anything that doesn't have meaning. If your loops are so large that you have to search for the variables within the loop, then your loop is too large. Refactore it to make it more readable!
-
Jon Limjap over 15 yearswhy not use a different letter then? or a whole word?
-
Antti Rasinen over 15 yearsI often use k to iterate over range and n or n_something to mark the size of the range. Otherwise I am complete agreement with you.
-
Mal Ross over 15 yearsPeople may argue that naming index variables is pointless, but I find it keep you in the habit of giving conscious thought to variable naming. Besides, if you're using C, you need to make sure you avoid variable name clashes with any other loops in the same method.
-
just mike over 15 yearsi certainly agree with @Ande Turner that "i" is self descriptive for 99.9% of programmers. however, you've made my point for me in your Java example... if you "refactor" your loop to not use "i" -- you can't do a global replace on the loop because of "someProcessing". you could if it was "ii" ;-)
-
John Millikin over 15 yearsIt's also much easier to search for / highlight "ii" or "jj" in an editor.
-
Derek Park over 15 yearsI find the first to be more readable. The longer names (especially the "_num" everywhere) just adds to the visual clutter.
-
Derek Park over 15 yearsI think your example it poor, because the problem is not with the index variables. The problem is with the loop conditions. If you're looking at the wrong piece of code (index names in this case), you're not going to find the problem, regardless of how you name things.
-
Derek Park over 15 yearsMal, use C99 and declare your loop variables in the loop heading (assuming you can choose to use C99, of course).
-
just mike over 15 yearsi agree with everything you say (except i've come to learn that it's better to say "recommendation" than "rule") -- and most people think my variable names are too long. "... do as your teammates do..." is one reason i used the "consistency" tag. another reason is of course "do as you yourself do".
-
Paul Stephenson over 15 yearsThe problem is not with the index variables, but I think a new code reader is less likely to spot that there is a bug in the first example. In the second, the expression "row_num < MAX_COLS" should definitely set alarm bells ringing, even with a casual browse through the code.
-
Thomas Koschel over 15 yearsIf the variable has no deeper sense (like "column" or "row" within an array for example) I use tripple letters, like iii, jjj, kkk.
-
Pitarou over 15 yearsWhy not abbreviate row_num to r and col_num to c? The meaning of the variable is just as clear to a casual reader, and you don't have so much visual clutter to deal with.
-
just mike over 15 yearsand of course even better would be: rr and cc! ;-)
-
petr k. over 15 yearsThis is not a relevant example, in my opinion. Moreover, the first example is much more readable and one is therefore much more likely to see the bug in there.
-
Mal Ross over 15 yearsOoops. Thanks for the heads-up. It's clearly been a long time since I used a C compiler.
-
Kibbee over 15 yearsI agree with finnw. Visual studio .Net lets you right click on a variable and "see all references". Any good IDE should provide this functionality.
-
Greg Rogers over 15 yearsIf you really want to include semantic information about the variable, typical convention is to do something like "iRow, iCol" just because absolutely everyone understands the convention that i is a looping variable.
-
Nat over 15 yearsIn which case they are actually meaningful names
-
jfs over 15 years@just mike: You can do a global replace: \bi\b
-
cynicalman over 15 yearsor if it's a cell based row/column layout based maybe common index variables like x and y can be used. But I find the first more readable.
-
Derek Park over 15 yearsOnorio, if you need loop variables on small loops to be "meaningful", I think I don't want to maintain your code. Seriously, if you can't handle "i" and "j" as indexes for tiny loops, I fear your code. I'm all for meaningful names, but there's a difference between meaningful and verbose.
-
epochwolf over 15 yearsI like that you used widget for each element in widgets
-
Mitch Wheat over 15 yearsI agree with others that have said, if you need to search through code for loop variables it is time to refactor.
-
Mitch Wheat over 15 yearsOnce again, I would have to question why you need to search for loop variables. Unless you are coding complex (complicated as oppose to Complex!) mathematical algorithms, loop vars should have a very limited scope.
-
Mitch Wheat over 15 years...assuming of course that nothing adds or removes anything from the Collection!
-
mattlant over 15 yearsPaul: you got my vote, i totally agree with your convention.using i & j you having to examine the way its used in the loop to find the bug (context). with *_num you can see the potential bug without the context. i & j can also be easily confused, as sometimes you do row major and other column major
-
Paul Stephenson over 15 yearsDerek, of course with a single-level loop with a body of three lines there shouldn't be any confusion using "i". Doing this though you'd have to have a threshold for "complex enough to switch to meaningful names". I am now in the habit of using names all the time -- editor auto-completion helps!
-
just mike over 15 yearsfrom Jeff's blog entry: codinghorror.com/blog/archives/001172.html here's some interesting code that every single one of us is using right here on SO: refactormycode.com/codes/333-sanitize-html (see line 22) ;-)
-
lbergnehr over 15 yearsAn interesting alternative I learned some years ago is to use "idx" (short for "index") and then, if you have a second or nested loop, use "jdx", "kdx" etc. So it continues the i,j,k tradition but is sort of readable.
-
Emile over 15 yearsCode is written once and read many many times. So it should be immediately clear what you read. For very small scope, a short "word" should be short but still distinguishable from a 1. I think ii en jj are good balance. For larger scopes I agree with the previous commenter and use a word.
-
petr k. over 15 yearsMaybe a bit personal thing, but I really do not like this naming convention. I find it ugly, confusing and higly unreadable. -1
-
Radvylf Programs over 4 yearsThing is,
i
is meaningful to pretty much anyone who programs. Why bother with typingindex
wheni
is so much shorter, and, in my opinion, more readable? -
Vaibhav Pallod about 2 yearsNever try to use 'i' in for loop for the interviews. just for Competitive coding is OK!