Idiom for consecutive loops?

Greg Jorgensen gregj at pdxperts.com
Fri Aug 10 07:16:19 EDT 2001


"Harald Kirsch" <kirschh at lionbioscience.com> wrote:

>>>
When programming in C I find myself writing consecutive loops like

  for(i=0; i<lastI; i++) {
    justDoIt(i);
    if( someTest(i) ) break;
  }
  /* the next loop continues were the last one stopped */
  for(/**/; i<lastI; i++) {
    doSomethingElse(i);
  }
<<<

That just doesn't look good to me. It's a usage not found in K&R--the
original source of all C idioms--or in any other C book I've read. I think
most C programmers think of for loop counters as local to the loop, even
though they aren't. C++ has this nice enhancement:

    for (int i=0; i < lastI; i++) { ... }

In that case i is local to the loop body.

I can see your idiom running into trouble if someone updated your code with
C++ enhancements, or if they inserted code between the two loops.

Following Guido's excellent "explicit rather than implicit" rule I'd opt for
something like this instead:

    for (i=0; i<lastI; i++) {
        int failedtest = 0;

        if !failedtest {
            justDoIt(i);
            failedtest = someTest(i);
        }
        else
            doSomethingElse(i);
    }


That said, I think Alex Martelli's example is a clear translation into
Python.

Greg Jorgensen
PDXperts LLC
Portland, Oregon, USA






More information about the Python-list mailing list