7

Possible Duplicate:
Why do most of us use 'i' as a loop counter variable?

I was just writing a nested loop and got to the point where I was using l and m as variables to control for loops, and I realized this could get very confusing; Ive already had a few bugs when I copied blocks of code to different levels. So I was thinking instead of using i,j,k I would use iSomething,iSomethingelse. So if I were going over a 3D model Id use

for(int iMesh=0;iMesh<numMesh;iMesh++)
    for(int iVertex=0;iVertex<meshes[iMesh].numVertex;iVertex++)

or maybe use the name of the variable Im iterating over:

for(int iMeshes

for(int iVerts

So I was wondering if there are any other standard or commonly used practices for doing this?

EDIT: Im wondering if there ARE any standards, not if its OK to do this

zacaj
  • 185
  • 1
  • 1
  • 4
  • 1
    Do whatever makes sense to you. I find that being more descriptive helps when reading the code later on. – Bernard Jan 01 '12 at 21:19
  • I think i,j,k are the best options. Or it,jt,kt for std::iterators. – Coder Jan 01 '12 at 21:25
  • 24
    Yes, there is a standard, it says "do not nest your loops so much that you run out of single-letter names (starting from 'i') for your loop variables." – Mike Nakis Jan 01 '12 at 21:27
  • don't use l its very confusing! – Lucina Jan 01 '12 at 21:33
  • 11
    If your loops are nested more than 3 levels deep, variable naming is *not* the most pressing problem in your code. – Michael Borgwardt Jan 02 '12 at 00:40
  • I use the `somethingIndex` format, such as `taxEntryIndex`. It is long, but I know exactly what it does. In case of some sort of grid, I would possibly use `x`, `y`, `z`, or `columnIndex`, `rowIndex`, `columnNum`, `rowNum`, etc. - whatever is most descriptive. – Job Jan 02 '12 at 00:44

7 Answers7

18

i,j and k are the standard counter variables. By using them you imply the variables are used to keep loop count and nothing else. If you use another more complex name then its less clear what the variable is used for.

If your counter variables are getting confusing then its a sign your code needs breaking up. i.e

for(int i=0;i<numMesh;i++)
   foo += CountVerticies(meshes[i]);
Tom Squires
  • 17,695
  • 11
  • 67
  • 88
  • 5
    +1 for "If your counter variables are getting confusing then its a sign your code needs breaking up." +100 if I could. – John R. Strohm Jan 01 '12 at 23:33
  • i,j,k are standard counter variables in fortran. We moved on since then. There is nothing standard about using crappy short variable names that are hard to find and spot. – Martin York Jan 02 '12 at 00:10
  • 8
    @LokiAstari: "The length of a variable's name should be proportional to the distance between its definition and its use, and inversely proportional to its frequency of use." No reason not to use i, j, k in limited scope. – quentin-starin Jan 02 '12 at 00:21
  • @qes: What!!! That just silly. A variable name should just have one requirement. It should be meaningful to **everybody** that reads it. The author the maintainer the beginner. Meaningful names should be the only test. The more frequently I use a variable the more meaningful it needs to be thus I would state the exact opposite of your rule. – Martin York Jan 02 '12 at 00:32
  • 9
    @Loki Astari: You really want to write code where a variable like "searchedForStringOccurrenceCount" appears 3 times per line, 10 lines in a row? Brevity has its advantages too. Also, the fact that i,j,k are used pervasively as loop counters has given them quite a bit of meaning. i is IMO more meaningful than "index", due to that. – Michael Borgwardt Jan 02 '12 at 00:38
  • @LokiAstari: Please notice of all the people answering and commenting on this question, you stand alone in that opinion. I suppose you'd write it like the psychotic code in this answer: http://programmers.stackexchange.com/a/86911/6735 – quentin-starin Jan 02 '12 at 00:41
  • @qes: All three of you :-). I have yet to see a reasonable argument from any of you. Arguing with three wrong people is easy :-) – Martin York Jan 02 '12 at 01:04
  • @MichaelBorgwardt: That's a straw man argument and you know it. Making variable names obnoxious long is just as bad as two short. The variable must be meaningful is the argument not that you need to compress a whole sentence into a variable name. – Martin York Jan 02 '12 at 01:05
  • 8
    @LokiAstari the reason you make variable names longer is to make them clearer. In the case of loop counters the clearest way is to express them the same way as every text book and the vast majority of coders. (ie i j and k) – Tom Squires Jan 02 '12 at 01:50
6

for standard looping people pick i,j,k because it is easy and in a lot of situations you don't have a meaning for it so i,j,k is meaningful also known by all developer so it is pretty close to a standard.

anyway if you need to change to something more meaningful, use the following guidelines that i picked from uncle bob book "Clean Code" note there is other things also to consider from the book, but this is what i thought fit to the looping name: -

  1. Use Intention-Revealing Names
  2. Avoid Disinformation
  3. Make Meaningful Distinctions
  4. Use Pronounceable Names
  5. Use Searchable Names
  6. Avoid Encodings (Hungarian Notation,Member Prefixes)
  7. Don't be cute
  8. Pick One Word per Concept

so the code will end up something like this more or less

        for(int cellPointer = 0; cellPointer < 10;cellPointer++)
        {
            for (int rowPointer = 0; rowPointer < 10; rowPointer++)
            {
               //do something
            }
        }

so when you go back to it you can understand it, if somebody from outside got to work on it after you i'll be readable to him

omarqa
  • 442
  • 3
  • 7
2

Use i, j, k... if your indexes have no "meaning".

I would use mesh, vertex, etc. without an i prefix instead, unnecessary Hungarian is evil.

You could also use stuff such as i0, i1, ... , in if you had a great number of nested loops, but I think more than 3-4 is unusual.

alex
  • 2,904
  • 1
  • 15
  • 19
  • Well then I always make an instance of the mesh Im on inside the loop called mesh, so that would conflict – zacaj Jan 01 '12 at 22:54
  • 2
    +1 for "unnecessary Hungarian is evil." Except I'd delete the "unnecessary": Hungarian is ALWAYS unnecessary, now that compilers know how to check types. – John R. Strohm Jan 01 '12 at 23:35
  • I dont use hungarian notation at all. If I need to know the type of something, thats what IDEs are for. The i wasnt supposed to be integer or anything, it was meant to be the i from i,j,k. Similarly, I usually use nVertex or nMesh for the number of things I have. – zacaj Jan 02 '12 at 00:10
  • -1: it can be seen in many coding standards that do not adopt Hungarian, so Hungarian-bashing does not apply to this case. the "i" in "iSomething" stands for "the count / loop index of Something", which is an index value and needs to be distinguished from the "Something" itself. Compare to the iterator versus the object it references. – rwong Jan 02 '12 at 02:15
  • @zacaj: also consider using a foreach construct if you are always referring to a single element within the loop – alex Jan 02 '12 at 21:03
  • @John R. Strohm: Hungarian can make sense for instance to signal unsafe variables (directly parsed user input) if your platform does not have a better method- but right now I can't think of any other valid examples – alex Jan 02 '12 at 21:03
  • @rwong: if you prefix a variable (esp. with a single letter) to denote something you are doing Hungarian (see Wikipedia for "apps Hungarian"). – alex Jan 02 '12 at 21:04
2

x,y, and z can be useful, especially when dealing with 2D or 3D coordinates.

Sure beats trying to remember that i = x and j = y, etc

Neil N
  • 602
  • 3
  • 11
1

i is standard parlance in mathematics to represent any integer in a series:

1, 2, 3 ... i, i+1, i+2 ... n.

The i stands for Integer (according to one of my former professors, I have no other cite.) So, at any given time in the execution of your loop, it would be accurate from a mathematical perspective to call it i.

Jacob G
  • 191
  • 1
  • 2
  • 6
0

One of the problems with using counter variables is that outside of the control logic for iteration they don't have any meaning.

Your instinct is correct that using iVertex is better than using i, as that adds clarity. However, the 'i' prefix tells you that the variable is an integer, which, while helpful in some circumstances isn't that useful with modern IDEs (this is one reason several answers argue against it).

What is best is just the general advice for naming a variable, which is based on what the variable contains. In this case, you're thinking of the variable based on how it is modified, but not on how it is used, or what it represents. A loop counter is incremented from some start to some end, but one can tell that by looking at the control structure. A better option is to name it based on how it is consumed by the body of the loop. In this case, iMesh is used as an index into the meshes array, so I would use something like 'meshId'.

One good reason for naming based on how something is intended to be used is that one can more easily detect code defects. For example, if I see "a = MeshId+2" I'm going to be very suspicious, because generally we don't want to be doing arithmetic operations on an Id, only index operations (meshes[MeshId]).

There are coding standards, but the problem is that there are too many of them. For further reading, you can try here:

http://en.wikipedia.org/wiki/Naming_convention_(programming)

Neal Tibrewala
  • 1,073
  • 7
  • 12
  • Nor should they have any meaning outside the iteration. The variables we are discussing are the loop counter for the iteration. If declared in the applicable scope as they should be, they have no meaning outside it. Variables with larger scope shouldn't be used as loop counters. – BillThor Jan 02 '12 at 04:54
  • @NealTibrewala: the i in iVertex probably does not stand for integer, it most likely is an abbreviation of index, now the index is an integer, but that is a coincidence. – jmoreno Feb 23 '13 at 21:22
-2

Choose a name that describes what the variable is for, such as

for (int loopCounter; loopCounter < 10; loopcounter++)
{
     if( loopCounter == doSomethingVal)
     {
          //do somthing

This is the approach I use so that you can read out the logic of the code without having to translate the code to "english" which makes it easier for a new person to read the code and understand the intent of the code (as the code reads out the logic as would be spoken between people). A lot of people will not stylistaclly like this though (cue downvoting!) beacuse they do not like verbose code, or are just too comfortable with i,j,k, or are using a memory limited language/hardware. The problem with using somehing short like just i is that if you are debugging or reading a large section of code and you come to a like like:

   ......
   someVar = i;

then you need to look up what i is, what someVar is and what this line means in terms of what the program is attempting to model. But if you have something like:

  ......
  currentItemId = loopItemCounter;

then it is more obvious what the intent of the command is without comments or having to read through a large chunk of code. For short functions/methods it doenst make much difference (because you can probably see all the code on one page), but if you have ever tried to debug a large program with variable names that are just i or kk you will see why I prefer to be more vebose in nameing.

I think that I picked up this practice after reading the book code complete, or one of the other programming pricipals books.

adam f
  • 380
  • 1
  • 3
  • 1
    IMHO, loopCounter is awful. It really doesn't add anything over i, which by convention means loopCounter, it means more typing and clutter. I'm all for descriptive variables, but sometimes conventions are good. – alex Jan 01 '12 at 22:48
  • @alex: completely disagree. `i` is not standard by any definition (unless you are using fortran). Using longer names makes maintaining the code easier. short names are hard to spot and find in the code and thus make reading harder. Have you ever searched the code for all instances of the variable `i` thats a real pain because of all the false positives. On the other hand `loopCounter` is unlikely to have any false positives and is much easier to see in the code. Now loopCounter may not be a great name but it is orders of magnitude bttter than `i` – Martin York Jan 02 '12 at 00:18
  • 7
    @LokiAstari: You are being patently absurd. `i` is standard by *convention* - the fact that a very large number of developers use it in the same way defines it in a standard way. And why on earth would you search for all instances of a variable like `i`? Do you not understand or use the concept of scope? One would use a name like `i` only when the length of its scope is short, which would make searching for "all instances" of it purposeless. – quentin-starin Jan 02 '12 at 01:11
  • @qes: The fact that you think you are in the majority is patently absurd. It has not been standard since we moved from Fortran. – Martin York Jan 02 '12 at 01:15
  • 4
    @LokiAstari: You do not live in reality. – quentin-starin Jan 02 '12 at 01:17
  • @qes: Convincing argument there. I have not seen i/j/k used as a loop variable for decades (apart from students just out of college). They don't do it for long as there code gets rejected at code review time by anybody that has done any time maintaining code. Now you fellow complainer took my argument to the absurd extreme by pointing out that absurdly long variables names are a pain. And this is true. Obnoxiously long names are going to get rejected just as quickly. – Martin York Jan 02 '12 at 01:18
  • 2
    Ya, obviously I'm the only one who sees using `i` as convention. http://programmers.stackexchange.com/questions/86904/why-do-most-of-us-use-i-as-a-loop-counter-variable http://stackoverflow.com/questions/454303/why-are-we-using-i-as-a-counter-in-loops http://stackoverflow.com/questions/4137785/why-are-variables-i-and-j-used-for-counters http://stackoverflow.com/questions/101070/what-is-an-ideal-variable-naming-convention-for-loop-variables http://programmers.stackexchange.com/questions/71710/using-single-characters-for-variable-names-in-loops-exceptions – quentin-starin Jan 02 '12 at 01:19
  • @qes: Did you actually read those questions :-) The basic are question of where the variables came from (Fortran/Maths) then the times when they argue about if it is good or not tend to agree with my point of view (meaningful) but don't be absurd with the name. – Martin York Jan 02 '12 at 01:34
  • 1
    http://programmers.stackexchange.com/questions/86904/why-do-most-of-us-use-i-as-a-loop-counter-variable "Why do **most of us** use 'i' as a loop counter variable?" Author of the question obviously sees it being a convention. So does the 90+ upvoted answer: "i and j have typically been used ...Most people seem to have seen little reason to change that. It's widely known and understood, and quite succinct" – quentin-starin Jan 02 '12 at 03:13
  • http://stackoverflow.com/questions/454303/why-are-we-using-i-as-a-counter-in-loops "Why are we using i as a counter in loops? ... I do it, you do it, everyone does it" Convention, again. Not a single answer suggests not using single letter variable names, despite being several hundred votes applied to those answers. – quentin-starin Jan 02 '12 at 03:14
  • http://stackoverflow.com/questions/101070/what-is-an-ideal-variable-naming-convention-for-loop-variables "What is an ideal variable naming convention for loop variables?" Top answer with ~30 votes: "1) For normal old style small loops - i, j, k" Second answer with another ~25 votes: "[If] 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" – quentin-starin Jan 02 '12 at 03:17
  • http://programmers.stackexchange.com/questions/71710/using-single-characters-for-variable-names-in-loops-exceptions "I've had a couple of discussions with a co-worker about the use of single letter variable names in certain circumstances inside our codebase, at which we both disagree. He favours more verbose naming convention for these, and I do not." Over one hundred votes across the top three answers favor `i`: "The name of a variable is only as relevant as its scope. Conventions improve readability. i and e are common conventions used for those small scoped variables..." and so on – quentin-starin Jan 02 '12 at 03:20
  • And all the comments here opposed to your view have all been upvoted multiple times, but yours have not been upvoted once. – quentin-starin Jan 02 '12 at 03:22