-3

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.

user4157124
  • 2,809
  • 13
  • 27
  • 42
ddp17
  • 41
  • 4
  • You need to initialize your variable i = 0. It currently is unitialized. – NoDakker Oct 15 '22 at 02:10
  • 1
    i will always be 4 since you're not incrementing it before the continue. Infinite loop. – Shawn Oct 15 '22 at 02:11
  • @Shawn Thanks. Wouldn't the increment after the printf statement do the work? Thank you! – ddp17 Oct 15 '22 at 02:13
  • 3
    Please refer https://stackoverflow.com/questions/33166912/how-the-continue-statement-works-in-for-loop-in-c . - Please do not create new questions with same queries. - Research more first and then raise only if you were unable to find any viable solution. – nitin angadi Oct 15 '22 at 02:14
  • 2
    "It does not process, as I assumed, whatever it is after the continue statement." I can't understand this expectation. Code runs in the order it's written, unless something explicitly changes that. So... you were expecting `continue` to... do nothing at all? – Karl Knechtel Oct 15 '22 at 02:27
  • No... It never gets called because of the continue. – Shawn Oct 15 '22 at 02:27

2 Answers2

4

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
    }
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
2

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.
Xin Cheng
  • 1,432
  • 10
  • 17