Is Decrementing/Incrementing Loop Variable Inside For Loop a Code Smell?

cloops

I have to read lines from a text file in sequential order. The file is a custom text format that contains sections. If some sections are out of order, I would like to look for the starting of the next valid section and continue processing.

Currently, I have some code that looks like this:

for (int currentLineIndex=0; currentLineIndex < lines.Count; currentLineIndex++ )
{
    //Process section here
    if( out_of_order_condition )
    {
        currentLineIndex--;//Stay on the same line in the next iteration because this line may be the start of a valid section.
       continue;
    }
}

Is this code smell?

UPDATE: I didn't mention this earlier, but the root cause of this kind of code was a complicated switch-case (typical when you're parsing).

I got rid of the incrementing/decrementing variable by using the "goto case" statement.

The structure now looks like this:

switch(state)
{
   case State.BOF:
       {
           //Process BOF case
       }
   case State.SeenHeader:
       {
           if( out_of_order_condition )
           {
               state = State.BOF;    //Reset the state to some respectable one

               //currentLineIndex--; Removed
               //continue;           Removed

               goto case State.BOF;//Handle this in this iteration itself. 
           }
       }
}

Best Answer

Well, since a code smell is something that makes you take a second look at it, which you yourself are doing, I'd say it definitely qualifies. However, code smells don't automatically need removing, just a hard look to make sure it's really the best way to solve the problem.

In this particular case, the reason you don't often see code like that is it can cause the loop to never terminate under certain input conditions. You're also commingling two different responsibilities into the loop: detecting section starts and processing a section. I would try to have one loop that only detects section boundaries, and once the entire section is known, pass the section contents to another function for processing.

It's also possibly a sign your format is complex enough that a homegrown parser is going to have difficulty catching all the boundary conditions. You might want to look into a full parser like bison or antlr.