cinfinite-loopdo-whilecontinue

Continue statement


The continue statement is for skipping the iteration but it doesn’t work as I expect. Here is my code:

int i = 0;
do
{
  if(i== 10)continue;
  printf("\n This is = %d",i);
  
  i++;
} while (i<20);

My understanding is that it will skip just

This is = 10

and rest it will print but it is skipping since

This is = 9 till 19

And here is the output

 This is = 0
 This is = 1
 This is = 2
 This is = 3
 This is = 4
 This is = 5
 This is = 6
 This is = 7
 This is = 8

why?

Also when I added for loop ahead of this loop that is entirely getting ignored and not getting executed?

int i = 0;
do
{
  if(i== 10)continue;
  printf("\n This is = %d",i);
  
  i++;
} while (i<20);

for(int a = 0 ; a<20 ; a++)
{
    if(a==10)continue;
    printf("\nHere = %d",a);
}

Output :

 This is = 0
 This is = 1
 This is = 2
 This is = 3
 This is = 4
 This is = 5
 This is = 6
 This is = 7
 This is = 8

Why? Please explain.


Solution

  • There are a couple of things going on here. First, The printf format string begins with a newline, but doesn't end with one. That's backwards from what is usually done. But because each printed string doesn't end in a newline, it is most likely being buffered until the next newline. So in fact, it's printing " This is = 9", but it isn't actually going through until the next newline, which never comes.

    The reason the next newline never comes is because, once i is 10, it goes into an infinite loop. Each time through, it does the comparison i == 10, which is true, so it immediately continues the loop, never executing the i++; increment. In the latter example, the for loop is never reached since it's stuck in the do/while loop.

    To fix the first problem, I suggest using a conventional format string, e.g. printf("This is = %d\n",i); With the newline at the end, the printf will normally be seen immediately (at least when not being redirected to a file). Alternatively, you can force the buffer to be flushed by calling fflush(stdout) immediately after calling printf. That will work regardless of where your newlines are.

    The second problem can be fixed by incrementing i prior to continuing, e.g.

    if (i == 10) {
        i++;
        continue;
    }
    

    But a cleaner way to write the loop would be:

    do {
      if (i != 10) {
          printf("This is = %d\n", i);
      }
      i++;
    } while (i<20);
    

    This shares the increment statement for both cases by avoiding the continue.