display | more...
For a long time, I was of the opinion that the for() loop in C was just a fancy version of while(). You can even see this in my node about the wonders of while(i--). However, I have recently realized something that makes for() simply more powerful: the continue statement.

Consider the following while loop:

int i=0;
while(i<10)
{
    some stuff;
    if(skipthisone)continue;
    some more stuff;
    if(skipthisone)continue;
    some more stuff;
    if(skipthisone)continue;
    some more stuff;
    i++;
}
Now, let's say what I wanted was to skip one or more of some more stuff, by setting skipthisone. Unfortunately, I also wanted that i++; statement to be executed regardless of a continue. Here's the possible solutions that I thought of at the time:
  • Put i++ with each continue.
    Blech. Not elegant at all.
  • Use a goto instead of continue, with a target right before i++;
    I'm sure that others would agree with me when I say that goto should be avoided.
  • Make a big if() nest.
    No thanks, I prefer my lines to start closer to the left side of my screen than the right.
So, I went with goto. It seemed like the better idea. However, I soon realized the following: for() could fix my problem! It is different (and better) because a continue will not skip the incrementing part.

The upgraded code:

int i=0;
for(;i<10;i++)
{
    some stuff;
    if(skipthisone)continue;
    some more stuff;
    if(skipthisone)continue;
    some more stuff;
    if(skipthisone)continue;
    some more stuff;
}
So, that's my rant. In some situations, for is just better. Mostly, you wouldn't need this stuff, though.

Perl fixes this problem with an optional continue block at the end of a loop block. This block is always executed after any calls to next, which is Perls version of a C continue statement.

Log in or register to write something here or to contact authors.