cout not working in the case of an infinite loop

雨燕双飞 提交于 2019-12-14 03:57:14

问题


int main(int argc, char* argv[]) 
{
    while(1)
    {
        cout<<"123";
    }
    return 0;
}

I wrote this small program which would print "123" and then go in an infinite loop. But it does not print anything on the screen. What is the reason for this?


回答1:


There can be two reasons.

Firstly, the output is most probably buffered. That is, the text sent to cout is not printed immediately, but kept in a buffer and printed only on flushing the buffer (which happens by cout.flush() or by printing endl).

Secondly, I suppose that an empty infinite loop is undefined behavior. That is, a program with an infinite loop can in fact do absolutely anything; in particular, an optimizer is allowed to optimize anything out of the program.




回答2:


Most likely the process CPU burn (due to the tight loop) has blocked the streaming to the console.

Technically though the behaviour of your program is undefined as, essentially, the loop does not have any input /output or side effects.

A compiler is permitted to optimise out your function body, which would also yield no output.



来源:https://stackoverflow.com/questions/32652591/cout-not-working-in-the-case-of-an-infinite-loop

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