Search code examples
coding-stylepseudocode

What is the correct way to convert from a for loop to a while loop?


I have a for loop of the form:

for (int i = from; i < to; i++) {
  // do some code (I don't know exactly what, it is subject to change)
}

And I want to convert it to a while loop (mostly because I want to play with the value of i inside the loop to go backwards and forwards and my co-worker thinks that doing this in a for loop is prone to problems. I tend to agree with him). So I wrote something like this:

int i = from;
while (i < to) {
  try {
    // do some code (I don't know exactly what, it is subject to change)
  } finally {
    i++;
  }
}

Which prompted some some loud comments. My reasoning is that you don't know what the code inside the loop does - it may (and does) have multiple continue commands.

As a response he wrote this:

int i = from - 1;
while (++i < to) {
  // do some code (I don't know exactly what, it is subject to change)
}

Granted its less lines, but I still think my code is more elegant - what do you think?


Solution

  • And I want to convert it to a while loop (mostly because I want to play with the value of i inside the loop to go backwards and forwards and my co-worker thinks that doing this in a for loop is prone to problems. I tend to agree with him).

    This is perfectly acceptable in most languages. There is no reason to avoid a for loop.