-1

I wrote the following code using a complier which was configured to be suitable with c89 standard using eclipse.

#include <stdio.h>

int main(void) {
    int i=0;
    printf("initial value for variable i is: %d\n",i);
    while (i<3)
    {
        if (i==1) {continue;}
        printf("%d\n",i);
        i++;
    }
    return 0;
}

The problem is that the code doesn't get excuted (No errors at all) and nothing shows in the console. When removing the following line of code if (i==1) {continue;} everything works correctly.

daniel
  • 1
  • 3
    When `i` is `1`, it doesn't get its value changed, so it is still `1` on the next iteration, and the next, and … it takes a long time to change from `1`. One advantage of a `for` loop is that it bundles the controls — you'd not see the problem with `for (i = 0; i < 3; i++)` as the loop; the `continue` would jump to the `i++` in the loop control. – Jonathan Leffler Jun 28 '19 at 15:56
  • @JonathanLeffler That's right, can u publish it as an answer to accept it – daniel Jun 28 '19 at 15:58
  • @JonathanLeffler Just something strange happened when using continue inside while loop does the code continue to run without checking the condition?! – daniel Jun 28 '19 at 16:01
  • 1
    It checks the condition on each iteration, but the value in `i` stays at `1` because the `continue` skips over the `i++;` line. So the condition never changes; the program doesn't stop. That is probably why no output appears — you say you are using Eclipse as your IDE, and it's "terminals" appear to the programs as a non-terminal, so I/O is fully buffered and no output appears until the buffer fills, you call `fflush(stdout)`, or the program _does_ stop. – Jonathan Leffler Jun 28 '19 at 16:03

1 Answers1

3

When i is 1, it doesn't get its value changed, so it is still 1 on the next iteration, and the next, and … it takes a long time to change from 1.

One advantage of a for loop is that it bundles the loop controls in a single line. You'd not see the problem with for (i = 0; i < 3; i++) as the loop; the continue would jump to the i++ in the loop control.

You say you are using Eclipse as your IDE. That's probably why no output appears at all. Its "terminals" appear to the programs as a non-terminal, so I/O is fully buffered (rather than line buffered as is normally the case with terminal output). That in turn means that no output appears until the buffer fills, you call fflush(stdout), or the program does stop. It's a known issue with Eclipse. You could call setvbuf(): add a line setvbuf(stdout, NULL, _IOLBUF, BUFSIZ); at the start to ensure line buffering is in effect.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278