Master Chief
Master Chief

Reputation: 3

why there is no output of following c code? is there any error of continue keyword

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;
}

Upvotes: 0

Views: 61

Answers (2)

user9706
user9706

Reputation:

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 the for() statement, and it will cause the size of the output to flush stdout:

#include <stdio.h>

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

Upvotes: 0

0___________
0___________

Reputation: 67835

I believe that you want to stop the loop when i is 10 not to have an indefinite loop

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

Upvotes: 1

Related Questions