簡體   English   中英

為什么下面的c代碼沒有output? continue 關鍵字是否有錯誤

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

這里我提供了 C 代碼,它沒有打印任何東西

#include <stdio.h> 

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

我相信您想在i10時停止循環。

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

i==10時,循環執行printf() 10 次,然后進入無限忙循環。 stdout 默認為行緩沖(參見 stdout(3)),因此它不會基於小尺寸被隱式刷新。 最干凈的解決方法是調用fflush()

#include <stdio.h>

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

您還可以通過將增量移動到for()來更改程序行為,並且超出 output 的大小會導致它被刷新:

#include <stdio.h>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM