Home > front end >  Could I get clarification on the continue statement?
Could I get clarification on the continue statement?

Time:10-15

I want clarification on the continue statement.

#include <stdio.h>
int main (void) {
    int i;

    while (i < 10) {
        if (i == 4) {
            i  ;
            continue;
        }
        printf("%d\n", i);
        i  ;
    }

    return 0;
}

This code outputs 0-9, skipping the number 4. I removed the increment statement below if statement:

 while (i < 10) {
        if (i == 4) {
            continue;
        }
        printf("%d\n", i);
        i  ;

I read continue will break one iteration of the loop. I assumed it will continue to the printf statement, move on and still output 0-9, skipping 4.

It is stuck in a loop and only printed 0, 1, 2 & 3.

CodePudding user response:

I'll try to make it a bit clearer:

int main (void) {
    int i = 0; // you need to initialize `i` before reading from it

    while (i < 10) {
        if (i == 4) {
            i  ;       // here you change the value
            continue;  // ok, go directly to the next lap in the while loop
        }
        // here i is: 0,1,2,3,5,6,7,8,9
        i  ;        
    }
}

and here's your second version:

int main (void) {
    int i = 0;

    while (i < 10) {   // <--------- 
                       //           |
        if (i == 4) {  // if 4, ---- 
            continue;  // when `i` reaches 4, when will `i  ` be reached?
        }              // hint: never

        i  ;           // 0=>1, 1=>2, 2=>3, 3=>4 ... never to be reached anymore
    }
}

CodePudding user response:

continue would end and start the next iteration of the CLOSEST loop only. The closest here means the current loop.

Notes:

  • if is not a loop.
  • for, while are loops.
  • Related