Why would C get stuck halfway through a while loop?

我怕爱的太早我们不能终老 提交于 2019-12-06 23:30:43

问题


When I compile and run this code (it's part of a much larger program), Linux gets halfway through the while loop, then simply stops working.

The code below prints time: 0 and then hangs, doing nothing else until I suspend the process. Why on earth would it print time: 0 but not the following line of sanity check?

while (i < 5)
{
    printf("time: %d\n",elapsedTime);
    printf("sanity check");
    foo();
    i++;
}

回答1:


Output usually is buffered and only written after a flush or newline. In

printf("sanity check");

there is no newline, so if you run in an endless loop after this, you won't see it. Replace it with

printf("sanity check\n");

or

printf("sanity check");
fflush(stdout);

and you'll see it.



来源:https://stackoverflow.com/questions/5124769/why-would-c-get-stuck-halfway-through-a-while-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!