Home > Software design >  why there is no output of following c code? is there any error of continue keyword
why there is no output of following c code? is there any error of continue keyword

Time:08-27

Here I have provided the C code and it is not print any thing

#include <stdio.h> 

int main(){ 
    int i=0;
    for(;;){
        if(i==10)
            continue;
        printf("%d ",  i);
    }
    return 0;
}

CodePudding user response:

I believe that you want to stop the loop when i is 10.

int main(){ 
    int i=0;
    for(;;){
        if(i==10)
            break;
        printf("%d ",  i);
    }
    printf("\n");
    return 0;
}
``

CodePudding user response:

The loop executes printf() 10 times before it goes into an infinite busy loop when i==10. stdout is line buffered by default (see stdout(3)) so it's not being flushed implicitly based on the small size. The cleanest fix is to call fflush():

#include <stdio.h>

int main() {
    for(int i = 0;;) {
        if(i==10) {
            fflush(stdout);
            continue;
        }
        printf("%d ",  i);
    }
    return 0;
}

You could also change the program behavior by moving the increment into for(), and size out of output would cause it to be flushed:

#include <stdio.h>

int main() {
    for(int i = 1;; i  ) {
        if(i!=10)
            printf("%d ", i);
    }
    return 0;
}
  •  Tags:  
  • c
  • Related