Graham Charlesby
Graham Charlesby

Reputation: 37

What naming conventions should I use on the second integer on a nested for loop?

I'm pretty new to programming, and I was just wondering in the following case what would be an appropriate name for the second integer I use in this piece of code

for (int i = 0; i < 10; i++)
{
    for (int x = 0; x < 10; x++)
    {
    //stuff
    }
}

I usually just name it x but I have a feeling that this could get confusing quickly. Is there a standard name for this kind of thing?

Upvotes: 3

Views: 622

Answers (4)

Aaron Anodide
Aaron Anodide

Reputation: 17196

Since you said you are beginning, I'd say it's beneficial to experiment with multiple styles.

For the purposes of your example, my suggestion is simply replace x with j.
There's tons of real code that will use the convention of i, j, and k for single letter nested loop variables.

There's also tons that uses longer more meaningful names.

But there's much less that looks like your example.

So you can consider it a step forward because you're code looks more like real world code.

Upvotes: 1

Fenton
Fenton

Reputation: 251172

You could opt to reduce the nesting by making a method call. Inside of this method, you would be using a local variable also named i.

for (int i = 0; i < 10; i++)
{
    methodCall(array[i], array);
}

I have assumed you need to pass the element at position i in the outer loop as well as the array to be iterated over in the inner loop - this is an assumption as you may actually require different arguments.

As always, you should measure the performance of this - there shouldn't be a massive overhead in making a method call within a loop, but this depends on the language.

Upvotes: 1

sarnold
sarnold

Reputation: 104080

Depending upon what you're iterating over, a name might be easy or obvious by context:

for(struct mail *mail=inbox->start; mail ; mailid++) {
    for (struct attachment *att=mail->attachment[0]; att; att++) {
        /* work on all attachments on all mails */
    }
}

For the cases where i makes the most sense for an outer loop variable, convention uses j, k, l, and so on.

But when you start nesting, look harder for meaningful names. You'll thank yourself in six months.

Upvotes: 6

Michael Robinson
Michael Robinson

Reputation: 29508

Personally I feel that you should give variables meaningful names - here i and x mean nothing and will not help you understand your code in 3 months time, at which point it will appear to you as code written by a dyslexic monkey.

Name variables so that other people can understand what your code is trying to accomplish. You will save yourself time in the long run.

Upvotes: 0

Related Questions