c语言 - 无限循环不起作用,使用 gcc 编译



当我向我的代码添加无限循环时,它不起作用。它只是运行,什么都不做。

例如,此代码不打印"hello"

#include <stdio.h>
int main(){
    printf("hello");
    while(1){
    }
    return 0;
}

但是此代码打印"hello"。

#include <stdio.h>
int main(){
    printf("hello");
    //while(1){ 
    //}
    return 0;
}

如何在代码中添加while(1)循环?

例如,在此代码中,不打印"hello"。

这是因为缓冲

您可以在printf()后立即调用fflush(stdout)以刷新缓冲区:

#include <stdio.h>
int main(){
    printf("hello");
    fflush(stdout);
    while(1){
    }
    return 0;
}

在第二种情况下,缓冲区在程序终止时刷新。

如果你想要的,首先,是无限打印"hello",那么你需要这样的东西。它将打印和冲洗放入无限循环

#include <stdio.h>
int main()
{
    while(1)
    {
        printf("hello");
        fflush(stdout);
    }
    return 0;
}

最新更新