0
clamore
2y

What's the correct way to do an iterator in a for loop?
Some teachers tells me that every iterator be named like line and row and other says i and j are the convention and you should name your iterator like that.

Comments
  • 4
    Sounds like they be confusing a FOR loop with a FOREACH loop.

    One you use an index (i) to iterate with, the other does it for you and naming the entry's is more sane.

    That's not to say you can't name the (i) to something that gives context like index, line, row, key, etc.
  • 2
    Honestly, I'm okay with either. If your iterator is mapping to a row or line then $row or $line is good. If you just want to identify or label some unknown and as yet unsorted number of arrays, I'd go with $i/$j.
  • 4
    Who gives a shit, just don't mix them.
  • 0
    If your looping through a collection (a foreach loop) then I’d use sometime like line or row.

    “For line in lines” is much easier to read that “for l in lines”

    Anything else would be okay with a single letter as long as it’s not completely irrelevant to what the loop is for
  • 1
    @C0D4 I can see where the confusion would come from, many courses would teach people to write write clean code like

    for popsicle in popsicles:

    then tell them to do some bubble sort where they expect them to write

    for j in range(i+1, n):

    How the fuck could a first timer differentiate between the two?
  • 0
    Hmm if you consider the iterator pattern, an iterable data structure implements next and hasNext. Some pseudo code to iterate using a for loop might be something like:

    for i=iter.next(); iter.hasNext(); i=iter.next()

    But that’s not very readable, and it would be better to use a foreach or while loop.

    I haven’t tried to iterate this way, but it might be cool to see if it works
  • 0
    No difference. But if you're making a generic iterator, better don't assign names like 'row' or 'word' or anything else too speciffic. I like 'it' or 'iter' or 'item', as they are also generic and fit any context.
  • 0
    Actually, I think $i and $j are best used when the number of iterations of the loop has been fixed by the programmer and not according to a varying integer number of group members. So if we're doing "Top Twenty this Year" a loop with $i;$i<=20;$i++ would, to me, be self-documenting. If it was for each thing in things, I'd maybe use $index, $counter or even $thingsCounter.
Add Comment