Continue statement in C

The continue statement interrupts the current step of a loop and continues with the next iteration. We do this, for some particular case, when we don’t want to execute the entire body of the loop, but still we want to go through the rest of the iterations.

Advertise on this site. I promise you will like the rates :)

This is for contrast of the break statement which stops the execution of the loop and transfers the control to the first line after the loop.

Here is a flowchart that demonstrates the behavior of continue:



Continue statement flowchart

Usage

continue:

  • must be used inside of a loop. Otherwise it makes no sense and the compiler will laugh at you (the error will look like this: "error: continue statement not within a loop")
  • will always be in a conditional statement. Otherwise part of the loop(the "More loop statements" block in the flowchart above) will be "dead code" which will never execute , which also makes no sense (but the compiler will be quiet)

Let's print all capital letters from A to G, with the exception of E.

char letter;
for(letter = 'A'; letter <= 'G'; letter++)
{
    if(letter == 'E')
        continue;
    printf("%c", letter);
}

Continue statement in nested loops

When we use nested loops we will interrupt only the body of the inner-most loop that surrounds the statement.

while(...)
{
    //body of the outer loop
    for(...)
    {
        //body of the inner loop
        if(...)
            continue;
    }
}

Here we will interrupt only the current execution of the for loop and transfer control to the next iteration of the for loop.

In the next example, continue is not part of the inner loop. When the “if” is true, we stop the execution of the while’s body and skip the entire for loop. The next iteration over the while will execute normally, including the inner loop.

while(...)
{
    //body of the outer loop
    if(...)
        continue;
    for(...)
    {
        //body of the inner loop
    }
} 

Summary

In practice the continue statement is rarely used. If you write code regularly, eventually you will need it at some point, but not as frequently as the break statement.

Related topics:

Previous keywordconst

Next keyworddefault

   Search this site: