【问题标题】:Code before while(1) does not run [duplicate]while(1) 之前的代码不运行[重复]
【发布时间】:2016-02-24 15:47:23
【问题描述】:

我有如下代码:

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("hello");

    while(1){
        // whatever here
    }
}

问题是:为什么会跳过第一条指令?它只运行循环,永远不会打印你好。我用 gcc 和 g++ 编译,结果相同。

【问题讨论】:

  • 好问题。完整的源代码和一个易于理解的问题。 (+1)

标签: c ansi-c


【解决方案1】:

确实运行,只是输出缓冲区没有在您的while 之前刷新

请改用printf("hello\n");。换行符将刷新缓冲区,因此立即将输出写入您的控制台。

【讨论】:

    【解决方案2】:

    你的假设是错误的,你的代码确实运行了,只是 stdout 没有被刷新,而是被缓冲了。

    printf("hello") 之后使用fflush(stdout),这会强制打印标准输出。

    而且,正如@Bathsheba 指出的那样,printf 中的换行符 ("\n") 也会强制它刷新,这在 in this SO question 中进行了解释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 2011-11-15
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 2021-06-23
      相关资源
      最近更新 更多