29

Loop counter conditions.

10 loops for example in this scenario:

i<=9
OR
i<10

Was arguing with a co-worker all week over this 😂

Comments
  • 30
    Second one
  • 0
    I am actually genuinely interested in this!
    What are the ups and downs of each of them?
  • 12
    The second one takes slightly less brain power to read.

    In terms of performance you'll not notice any difference, so go for the one your co-workers will need to use slightly less brain power on.
  • 7
    The second one lets you see the count and not the final index in 0-based arrays which is why I like it...

    for (int i = 0; i < myList.Count; i++) { ...
  • 27
    Both:

    <= for when the number itself has meaning.
    < for limits or lengths of arrays/strings/etc.

    Pick the one that conveys the most information about your intent in the most readable way.
  • 3
    It depends on what the loop is for, if you want people to know it's specifically running 9 times then the first one
  • 2
    @Ashkin this is what I do.+++++
  • 0
    @Cyan101 is it running 9 times??
  • 0
    If it is to loop through a collection, clearly the second one. When you need a specific range I rather like the first.
  • 3
    This has actually been analysed.

    Dijkstra wrote about bounds checking and the best way that minimises errors.

    Basically:

    0 <= x < N

    is the way to do it.
  • 0
    @LoveBytes @sha-i it is widely said that explicitly stating collection.size() is not slower than keeping local copy of the size.
Add Comment