Search code examples
for-looplanguage-agnosticloop-counter

Should I expect to see the counter in `for` loop changed inside its body?


I'm reading someone else's code and they separately increment their for loop counter inside the loop, as well as including the usual afterthought. For example:

for( int y = 4; y < 12; y++ ) {
    // blah
    if( var < othervar ) {
        y++;
    }
    // blah
}

Based on the majority of code others have written and read, should I be expecting to see this?


Solution

  • The practice of manipulating the loop counter within a for loop is not exactly widespread. It would surprise many of the people reading that code. And surprising your readers is rarely a good idea.

    The additional manipulation of your loop counter adds a ton of complexity to your code because you have to keep in mind what it means and how it affects the overall behavior of the loop. As Arkady mentioned, it makes your code much harder to maintain.

    To put it simply, avoid this pattern. When you follow "clean code" principles, especially the single layer of abstraction (SLA) principle, there is no such thing as

    for(something)
      if (somethingElse)
       y++
    

    Following the principle requires you to move that if block into its own method, making it awkward to manipulate some outer counter within that method.

    But beyond that, there might be situations where "something" like your example makes; but for those cases - why not use a while loop then?

    In other words: the thing that makes your example complicated and confusing is the fact that two different parts of the code change your loop counter. So another approach could look like:

     while (y < whatever) {
       ...
       y = determineY(y, who, knows);
     }
    

    That new method could then be the central place to figure how to update the loop variable.